Python 最近 60 个月末

ar1*_*994 2 python datetime

这是我在这里的第一篇文章,所以如果我做错了,请告诉我......

我希望从参考日期开始计算过去 60 个月中每个月的最后一天。

例如,如果参考日期是今天(2014 年 8 月 21 日),那么最后一个月底是 2014 年 7 月 31 日,而前一个月底是 2014 年 6 月 30 日……

有谁知道如何在python中做到这一点?

谢谢!

bgp*_*ter 5

这是使用datetime模块的更简单/更清洁的方法:

>>> import datetime
>>> def prevMonthEnd(startDate):
...    ''' given a datetime object, return another datetime object that
...        is set to the last day of the prevoius month '''
...    firstOfMonth = startDate.replace(day=1)
...    return firstOfMonth - datetime.timedelta(days=1)
...
>>> theDate = datetime.date.today()
>>> for i in range(60):
...    theDate = prevMonthEnd(theDate)
...    print theDate
...
2014-07-31
2014-06-30
2014-05-31
2014-04-30
2014-03-31
2014-02-28
2014-01-31
2013-12-31
(etc.)
Run Code Online (Sandbox Code Playgroud)