我们可以使用dateutil pakage计算两个日期之间的年数,月数,天数。在我的代码中,我使用索引来获取年,月和日。但是dateutil包 - ' relativedelta' object不支持索引。请求帮助计算两个日期之间的年数,月数,天数而不使用包裹。
from datetime import datetime, date, time
class Employee:
raise_amt = 1.05
def __init__(self, first, last, pay, birthdate='07-03-1991', joindate='31-12-2013'):
self.first = first
self.last = last
self.pay = int(pay)
self.birthdate = birthdate #instance variable
self.joindate = joindate
self.first = first + "." + last + "@company.com"
def exeperience(self): #calculating experience
self.joindate = datetime.strptime(self.joindate, '%d-%m-%Y')
today = date.today()
experience = ((today.year-self.joindate.year),(today.month-self.joindate.month),(today.day - self.joindate.day))
return experience
@classmethod
def from_string(cls, emp_str):
first, last, pay = emp_str.split('-')
return cls(first, last, pay)
emp_str_1 = 'Nanda-Reddy-45412'
emp_1 = Employee.from_string(emp_str_1)
sync=emp_1.exeperience()
print('Employee experience is{} years {} months {}days:'.format(sync[0],sync[1],sync[2]))
输出:员工经验为3年-2个月-9天:但确切 输出应该是2年10个月22天。帮助我得到这个 输出
答案 0 :(得分:1)
实际上,您无法以相对形式表示日期增量" YYYY年,MM月和DD天"确切地说,由于每个月的日子不同而且有闰年,你的结果将是模棱两可的。但如果您只是需要一些描述,请参阅以下代码:
def exeperience(self): #calculating experience
self.joindate = datetime.strptime(self.joindate, '%d-%m-%Y')
today = date.today()
days = (today - self.joindate).days
years, days = days // 365, days % 365
months, days = days // 30, days % 30
return (years, months, days)
答案 1 :(得分:0)
我已经定义了一个函数daysBetweenDates(year1,month1,day1,year2,month2,day2),它们将提供所需的结果。我还创建了这个主函数中使用的较小的子函数。使用的闰年定义是 - 如果它们是世纪年,可以被4整除,可以被400整除。感谢。
def daysinyear (year):
if year % 4 == 0:
days = 366
if year % 100 == 0 and year % 400 !=0:
days = 365
return days
return days
days = 365
return days
def daysbwwholeyears(year1,year2):
i=year1
days=0
while i<=year2:
days = daysinyear(i) + days
i=i+1
return days
def daystodate (month,day,year):
days = summonth (month - 1,year) + day
return days
def summonth (month,year):#is mahine ke end tak kitne din ho chuke
if year % 4 == 0:
daysinmonth = [31,29,31,30,31,30,31,31,30,31,30,31]
days = 0
i=0
while i< month:
days = days + daysinmonth[i]
i=i+1
return days
daysinmonth = [31,28,31,30,31,30,31,31,30,31,30,31]
days = 0
i=0
while i< month:
days = days + daysinmonth[i]
i=i+1
return days
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
if year2 - year1 ==0:
days = daystodate(month2,day2,year2) - daystodate(month1,day1,year1)
return days
if year2 - year1 ==1:
days = daysinyear(year1) - daystodate(month1,day1,year1) + daystodate(month2,day2,year2)
return days
days = daysbwwholeyears(year1+1,year2-1) + daysinyear(year1) - daystodate(month1,day1,year1) + daystodate(month2,day2,year2)
return days