5

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"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anjaneyulubatta505
  • 10,713
  • 1
  • 52
  • 62
  • `datetime.datetime.now() + datetime.timedelta(days=days)` will give you the date you want in the future. Just substract year, month (assuming 12 months) and day from each other... – 301_Moved_Permanently Jul 31 '15 at 06:23
  • You can find answer here http://stackoverflow.com/questions/1551382/user-friendly-time-format-in-python – sajith Jul 31 '15 at 06:28
  • You could use the `divmod` function as well: `year, days = divmod(days, 365)`, etc. – chepner Apr 20 '16 at 20:20

1 Answers1

9

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)
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119