如何在python中获取过去四个月的第一个和最后一个日期

时间:2017-11-28 14:19:23

标签: python python-datetime

我想了解过去四个月的第一个和最后一个日期。我尝试过以下概念,

@staticmethod
def getDateRangeByMonth(year, month):
    """

    :param year:
    :param month:
    :return:
    """
    if year is None:
        today = datetime.today()
        year = today.year
    if month is None:
        today = datetime.today()
        month = today.month
    _, num_days = calendar.monthrange(year, month)
    since = datetime.datetime.strptime(str(datetime.date(year, month, 
    1)), "%Y-%m-%d")
    till = datetime.datetime.strptime(str(datetime.date(year, month, 
    num_days)), "%Y-%m-%d")

    return since, till



 for i in range(0,4):
     today = datetime.today()
     since, till = getDateRangeByMonth(today.year, today.month - i)

我知道这个概念会在过去的一个月与前一年相比下降,就像月份是1月或者1月那样,那么年份必须改变。

如何改变这个或我的错误

提前致谢

2 个答案:

答案 0 :(得分:1)

在下面的代码中,诀窍是datetime模块提供timedelta提前一天,date.replace提供一个月的第一天。所以这是一个简单的函数:

def start_end_by_month(dat, delta):
    d = dat.replace(day = 1)
    till = []
    since = []
    for i in range(delta):
        d = d - datetime.timedelta(days=1)
        till.append(d)
        d = d.replace(day=1)
        since.append(d)
    return since, till

用法示例:

>>> start_end_by_month(datetime.date(2008, 3, 10), 5)
([datetime.date(2008, 2, 1), datetime.date(2008, 1, 1), datetime.date(2007, 12, 1),
datetime.date(2007, 11, 1), datetime.date(2007, 10, 1)],
[datetime.date(2008, 2, 29), datetime.date(2008, 1, 31), datetime.date(2007, 12, 31),
datetime.date(2007, 11, 30), datetime.date(2007, 10, 31)])

显示很容易跳过一年的边界......

答案 1 :(得分:0)

这是一个修改过的函数,它为您提供了前几个月的开始和结束日期所需的数量:

def getPrevDateRangeByMonth(year, month, prev):

    if year is None:
        today = datetime.date.today()
        year = today.year
    if month is None:
        today = datetime.date.today()
        month = today.month
    since = []
    till = []
    for i in range(prev):
        if month == 0:
            year -= 1
            month = 12
        _, num_days = calendar.monthrange(year, month)
        since.append(datetime.datetime.strptime(str(datetime.date(year, month, 1)), "%Y-%m-%d"))
        till.append(datetime.datetime.strptime(str(datetime.date(year, month, num_days)), "%Y-%m-%d"))
        month -= 1
    return since, till

prev = 4
today = datetime.date.today()
since, till = getPrevDateRangeByMonth(2017, 3, prev)
for i in range(prev):
    print(since[i], till[i])

我已将datetime.today()更改为datetime.date.today(),因为它对我有用,您应该将其更改回来。