I am giving number of days to convert them to years, months, weeks and days, but I am taking default days to 365 and month days to 30. How do I do it in an effective way?
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"
So if you want to convert the number of days to years, all you need to do is divide the number of days by 365.
datetime() module Python has a built-in datetime module that assists us in resolving a number of date-related issues. We just input the two dates with the date type and subtract them to discover the difference between the two dates, which gives us the number of days between the two dates.
It is much easier if you use a third-party library named 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With