如何在 Python 中获取下个月的第一天?例如,如果现在是 2019-12-31,则下个月的第一天是 2020-01-01。如果现在是 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)
这是正确的吗?有没有更好的办法?
原文由 Flux 发布,翻译遵循 CC BY-SA 4.0 许可协议
这是一个仅使用标准
datetime
库的单行解决方案:例子: