How do I convert days into years and months and days in python? for example: if someone were to be 5,538 days old. how can I display that through years and months and days like this : 15 years old 2 months and 1 day
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 ? 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
.
because rdelta.months gives you the remaining months after using full years, it doesn't give you the actual difference in 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.