有没有最好的方法来改变Python中给定的天数到几个月的工作日?

时间:2015-07-31 06:12:17

标签: python django datetime

我将天数转换为数年,数月,数周和数天,但我将默认天数设为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"

1 个答案:

答案 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)