我将天数转换为数年,数月,数周和数天,但我将默认天数设为365天和30天。我如何以有效的方式进行此操作?
def get_year_month_week_day(days):
year = days / 365
days = days % 365
month = days / 30
days = days % 30
week = days / 7
day = days % 7
return year,month,week,day
def add_s(num):
if num > 1:
return 's '
return ' '
@register.filter
def daysleft(fdate):
cdate = datetime.datetime.now().date()
days = (fdate.date() - cdate).days
if days == 0:
return "Today"
elif days == 1:
return "Tomorrow"
elif days > 0:
year, month, week, day = get_year_month_week_day(days)
print year, month, week, day
days_left = ""
if year > 0:
days_left += str(year) + " year" + add_s(year)
if month > 0:
days_left += str(month) + " month" + add_s(month)
if week > 0:
days_left += str(week) + " week" + add_s(week)
if day > 0:
days_left += str(day) + " day" + add_s(day)
return days_left + " left"
else:
return "No time left"
答案 0 :(得分:8)
如果您使用名为python-dateutil
的第三方库:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.now()
>>> td = datetime.timedelta(days=500)
>>> five_hundred_days_ago = now - td
>>> print relativedelta(now, five_hundred_days_ago)
relativedelta(years=+1, months=+4, days=+13)