如何在Python中使用datetime获取给定日期的下个月同一天
我知道可以用datetime.timedelta来计算从某个日期起过几天后的日期。
daysafter = datetime.date.today() + datetime.timedelta(days=5)
但是好像没有像datetime.timedelta(month=1)
这样的用法。
13 个回答
12
你可以使用 calendar.nextmonth
这个功能(来自 Python 3.7)。
>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)
不过要注意,这个功能并不是为了让大家公开使用的,它是用在 calendar.Calendar.itermonthdays3() 这个方法里的。所以它不会检查你输入的月份值:
>>> calendar.nextmonth(year=2019, month=60)
(2019, 61)
在 Python 3.8 中,这个功能已经被实现为内部函数了。
45
当然没有了——如果今天是1月31日,下个月的“同一天”是什么呢?显然,2月31日是不存在的,所以没有一个“正确”的解决办法。而且,datetime
模块也不会去猜测提问者心里认为的“显而易见”的解决方案,因为那根本是个不可能的问题;-)。
我建议:
try:
nextmonthdate = x.replace(month=x.month+1)
except ValueError:
if x.month == 12:
nextmonthdate = x.replace(year=x.year+1, month=1)
else:
# next month is too short to have "same date"
# pick your own heuristic, or re-raise the exception:
raise