现在和生日之间的差异,以年,月,日,分钟为单位 [英] Difference between now and birthdate in years, months, days, mintues

查看:43
本文介绍了现在和生日之间的差异,以年,月,日,分钟为单位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import datetime
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
#This returns a timedelta object -> datetime.timedelta(7629, 36148, 156646)

现在,我想精确地将timedelta对象转换为年,月,日和秒.我知道我可以喜欢difference.days//365来获得年份,依此类推.是否有其他方法或方法来转换此timedelta对象?年,月,日和分钟准确而又轻松地?

Now i want to convert precisely the timedelta object in years, months, days and seconds.. I know i can do like difference.days // 365 to get years and so on.. Is there any other way or methods to convert this timedelta objects in Year, months, days and minutes precisely and easily?

推荐答案

添加问题注释 timedelta 可让您.因此,如果要计算年份,则应执行一些简单的算术计算.这是计算年份的简单方法.一些代码添加您的给定代码.

Adding with the question comment timedeltagives you days and seconds. So if you want to calculate the year than you should perform some simple arithmetic calculation. Here Is simple way to calculate the year. some code adding your given code.

import datetime
import math
birthday = datetime.datetime(1996,8,15)
differnce = datetime.datetime.now() - birthday
year = differnce.days//(365.25)
month = (differnce.days-year*365.25)//(365.25/12)
day = ((differnce.days-year*365.25) - month*(365.25/12))
print('Years=',int(year),' Months=',int(month), ' Days=',int(math.ceil(day)))

此处 365.25 几乎可以正确地用于leap年的计算.有关更多详细信息,请在此处

here the 365.25 is used for almost correctly for leap year calculation. For more details check here and here.

这篇关于现在和生日之间的差异,以年,月,日,分钟为单位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆