期间的开始和结束

时间:2017-09-26 12:45:12

标签: python

除了月份之外,还有一种方法可以get_month_day_range()week扩展year功能吗?

该方法可以定义为get_day_range(period, date),该句点可以是weekmonthyear

import datetime

from dateutil.relativedelta import relativedelta

def get_month_day_range(date):
    """
    For a date 'date' returns the start and end date for the month of 'date'.

    Month with 31 days:
    >>> date = datetime.date(2011, 7, 27)
    >>> get_month_day_range(date)
    (datetime.date(2011, 7, 1), datetime.date(2011, 7, 31))

    Month with 28 days:
    >>> date = datetime.date(2011, 2, 15)
    >>> get_month_day_range(date)
    (datetime.date(2011, 2, 1), datetime.date(2011, 2, 28))
    """
    last_day = date + relativedelta(day=1, months=+1, days=-1)
    first_day = date + relativedelta(day=1)
    return first_day, last_day

if __name__ == "__main__":
    import doctest
    doctest.testmod()

到目前为止我得到了这个结果:

def get_period_day_range(date, period='month'):
        last_day = None
        first_day = date + relativedelta(day=1)

        if period == 'month':
            last_day = date + relativedelta(day=1, months=1, days=-1)
        elif period == 'week':
            last_day = date + relativedelta(day=1, weeks=1, days=-1)
        elif period == 'year':
            last_day = date + relativedelta(day=1, years=1, days=-1)
        return first_day, last_day

它不是一直都在工作。它与week的{​​{1}}和datetime.datetime(2017, 7, 10)的{​​{1}}无效。我该怎么办呢?有什么建议吗?

请注意,该功能的目的是为了给我们一定时期的开始和结束日期,具体取决于我们输入的日期。例如,如果我将datetime.datetime(2017年,7月10日)与年份一起提供,它将为year提供,或者为datetime.datetime(2017, 7, 5)提供一周,则输出将为(datetime.datetime(2017, 1, 1), datetime.datetime(2017, 12, 31))

1 个答案:

答案 0 :(得分:3)

您做错了,只是复制上面的代码而不查看您正在使用的库的文档(链接:http://dateutil.readthedocs.io/en/stable/relativedelta.html

你需要做这样的事情(未经测试):

from dateutil.relativedelta import *

def get_period_day_range(date, period='month'):
    if period == 'month':
        # Then we want day 1 of that month and previous day of the 
        # day 1 of the next month, hence months = 1 (next month) and
        # days = -1 (previous date)
        first_day = date + relativedelta(day=1)
        last_day = date + relativedelta(day=1, months=1, days=-1)
    elif period == 'week':
        # Last monday
        first_day = date + relativedelta(weekday=MO(-1))
        # Next sunday
        last_day = date + relativedelta(weekday=SU)
    elif period == 'year':
        # First day of the year, note day and month are singular so they
        # are not relative terms (read the doc)
        first_day = date + relativedelta(day=1, month=1)
        # Last day is always 31 December
        last_day = date + relativedelta(day=31, month=12)
    return first_day, last_day