Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a best way to change given number of days to years months weeks days in Python?

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"
like image 959
anjaneyulubatta505 Avatar asked Jul 31 '15 06:07

anjaneyulubatta505


People also ask

How do you convert days into days months and years?

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.

How do I calculate days difference in Python?

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.


1 Answers

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)
like image 141
Ozgur Vatansever Avatar answered Oct 01 '22 15:10

Ozgur Vatansever