【发布时间】:2019-12-12 16:49:55
【问题描述】:
如何在 Python 中获取下个月的第一个日期?例如,如果现在是 2019 年 12 月 31 日,那么下个月的第一天就是 2020 年 1 月 1 日。如果现在是 2019-08-01,那么下个月的第一天就是 2019-09-01。
我想出了这个:
import datetime
def first_day_of_next_month(dt):
'''Get the first day of the next month. Preserves the timezone.
Args:
dt (datetime.datetime): The current datetime
Returns:
datetime.datetime: The first day of the next month at 00:00:00.
'''
if dt.month == 12:
return datetime.datetime(year=dt.year+1,
month=1,
day=1,
tzinfo=dt.tzinfo)
else:
return datetime.datetime(year=dt.year,
month=dt.month+1,
day=1,
tzinfo=dt.tzinfo)
# Example usage (assuming that today is 2021-01-28):
first_day_of_next_month(datetime.datetime.now())
# Returns: datetime.datetime(2021, 2, 1, 0, 0)
正确吗?有没有更好的办法?
【问题讨论】:
-
看起来正确。你得到错误的答案吗?
-
另外,只有 4 行代码,所以你所拥有的几乎是最优化的解决方案,除非你有一些非常具体的要求。你可以把它减少到 1 行,但这只会降低它的可读性。