这是我在这里发表的第一篇文章,如果我做错了,请告诉我......
我希望从引用日期开始计算过去 60 个月中每个月的最后一天。
例如,如果引用日期是今天(2014 年 8 月 21 日),则最后一个月末是 2014 年 7 月 31 日,而之前的月末是 2014 年 6 月 30 日...
有谁知道如何在Python中做到这一点吗?
谢谢!
最佳答案
这是一种利用 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.)
关于Python 过去 60 个月末,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431280/