python - 员工退休年限如何计算
问题描述
我正在使用带有 Django 框架的 python 构建 HR 应用程序,我在计算员工的退休年份时遇到问题,例如,如果员工输入他/她的出生日期,让系统计算他/她的退休年份或剩余多少年退休。员工60岁退休
收到此错误:
TypeError at /staffprofile/profile_entry/
unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
Request Method: POST
Request URL: http://0.0.0.0:8080/staffprofile/profile_entry/
Django Version: 1.8
Exception Type: TypeError
Exception Value:
unsupported operand type(s) for -: 'datetime.date' and 'datetime.datetime'
Exception Location: /home/bakceesay/djangoapps/NAO/venv/src/staffprofile/views.py in profile_entry, line 57
这是我在views.py 中的代码
from __future__ import unicode_literals
from django.shortcuts import get_object_or_404, render, redirect
from django.contrib.auth.models import User
from django.http import HttpResponse, HttpResponseRedirect # HttpResponse allows the get_absolute_url to work ## and HttpresponseRedirect redirects page after a process
from .models import *
from .forms import *
from django.contrib import messages
from datetime import datetime, timedelta
def profile_entry(request):
title = 'ADD YOUR PROFILE INFORMATION'
form = ProfileForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
date_of_birth = instance.date_of_birth
age_days = (datetime.now().date() - date_of_birth)
age = (age_days/365)
rem_yrs = (60 - int(age))
instance.date_of_retirement = rem_yrs
instance.save()
messages.success(request, 'Successfully Saved')
return redirect('/profile/profile_detail')
context = {
"title": title,
"form": form,
}
return render(request, "profile_entry.html",context)
模型.py
[address = models.CharField(max_length=30, blank=True, null=True)
date_of_birth = models.DateTimeField(blank=True, null=True)
email_address = models.CharField(max_length=30, blank=True, null=True)
phone_number = models.CharField(max_length=30, blank=True, null=True)
date_of_hire = models.DateTimeField(blank=True, null=True)
date_of_termination = models.DateField(blank=True, null=True)
date_of_retirement = models.CharField(max_length=30, blank=True, null=True)][1]
解决方案
您肯定是通过获取当天和他们生日的日期时间对象来开始的。通过以下方式创建退休对象:
retirement = date_of_birth.replace(year=date_of_birth.year+60)
然后通过获得财产获得退休年
retirement.year
最后,得到剩余的年数
retirement.year-datetime.now().date().year
由于闰年,我不会将天数除以 365。但是,此方法将四舍五入此人的当前年龄,并且不存在一年的小数部分。如果您想要更精确,我会添加几个月而不是一年的分数。如果需要,只需使用 datetime 的 .month 属性。
推荐阅读
- mysql - 在 MySQL 和 PHP 中将两条记录与一个公共字段合并并增加一个字段
- asp.net-mvc - AspNet Core 2 No service for type 'Microsoft.AspNetCore.Http.HttpContext' 会话问题
- actions-on-google - Actions on Google:如何使用 NodeJS 实现数据库和用户实体(会话)
- ios - 如何在 ios-charts 上添加长按?
- javascript - 如何从值0到1获得从红色到白色的平滑渐变值?
- javascript - CSS 转换仅在 Chrome 开发工具打开时有效
- javascript - 使用 jQuery 设置整个选择值
- regex - 正则表达式负面展望没有给出预期的结果
- sonarqube - 声纳认证
- square - TransactionID 中的最大字符数是多少?