[英]How do I convert days into years and months in python?
How do I convert days into years and months and days in python? 如何在python中将天转换成年,月和日? for example: if someone were to be 5,538 days old.
例如:某人的年龄为5538天。 how can I display that through years and months and days like this : 15 years old 2 months and 1 day
我如何通过这样的年月日来显示该信息:15岁2个月零1天
print "Please enter your birthday"
bd_year = int(raw_input("Year: "))
bd_month = int(raw_input("Month: "))
bd_day = int(raw_input("Day: "))
from datetime import date
now = date.today()
birthdate = date(int(bd_year), int(bd_month), int(bd_day))
age_in_days = now - birthdate
print "Your age is %s" % age_in_days
How about using dateutil.relativedelta.relativedelta
from the dateutil
library ? 如何从
dateutil
库中使用dateutil.relativedelta.relativedelta
? For example: 例如:
from dateutil.relativedelta import relativedelta
rdelta = relativedelta(now, birthdate)
print 'Age in years - ', rdelta.years
print 'Age in months - ', rdelta.months
print 'Age in days - ', rdelta.days
Using dateutil.relativedelta.relativedelta
is very efficient here: Except for using .months
or .days
. 在这里使用
dateutil.relativedelta.relativedelta
非常有效:除了使用.months
或.days
。
because rdelta.months gives you the remaining months after using full years, it doesn't give you the actual difference in months. 因为rdelta.months会为您提供使用整年后的剩余月份,所以它不会为您提供实际的月份差异。 You should convert years to months if you need to see the difference in months.
如果需要查看月份之间的差异,则应将年份转换为月份。
def deltamonths(x):
rdelta = relativedelta(now, birthdate)
return rdelta.years*12 + rdelta.months
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.