Python 过去 60 个月末

标签 python datetime

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

我希望从引用日期开始计算过去 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/

相关文章:

c# - 日期时间转移到下一个预定义日期

python - 用numpy计算矩阵乘积

python - SQLAlchemy:如何向现有表添加列?

python 2.7 - 设置 2 个记录器

python - 如何使 pythons datetime 对象以小写形式显示 AM 和 PM?

c# - 在 C# 中将时间戳字符串转换为 DateTime 对象

python - 如何在 Django 中将 UTC 时间转换为用户本地时间?

python - 如何递归地将返回列表的 Celery 任务链接到组中?

python - 显示列表的所有可能分组,仅给出子列表的数量(长度可变)

php - 从用户输入的选定日期在 MySQL 中始终存储为 "1970"