扩展get_month_day_range()方法

时间:2017-09-26 05:28:26

标签: python

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

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

import datetime

# requires python-dateutil (http://labix.org/python-dateutil)
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()

更新

@ cricket_007工作正常,但不是所有时间。它与week的{​​{1}}和datetime.datetime(2017, 7, 10)的{​​{1}}无效。我怎么能解决它?

1 个答案:

答案 0 :(得分:1)

我会从这样的事情开始

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

“周”逻辑并不能很好地适用于day=1。换句话说,您需要以某种方式确定给定日期周的“开始”在哪里