python 获取明天(新年)的时间戳失败,日期超出了月份的范围

3htmauhk  于 2023-01-01  发布在  Python
关注(0)|答案(1)|浏览(303)

我正在尝试获取明天的时间戳。这已经工作了几天,今天(新年前夜)失败,并显示错误消息
Traceback (most recent call last): File "C:/Users/Tomean/AppData/Local/Programs/Python/Python310/Scripts/testtime.py", line 19, in print("Timestamp_Tomorrow: ", int(datetime(today.year, today.month, today.day + 1, 0 , 0, 0).timestamp())) ValueError: day is out of range for month

from datetime import datetime
from pytz import timezone
study_timezone = timezone('Europe/London')
today = study_timezone.localize(datetime.now())
print("today",today)
print("Timestamp_Tomorrow: ", int(datetime(today.year, today.month, today.day + 1, 0 , 0, 0).timestamp()))

这个问题我怎么解决呢?是因为明天正好是新年呢,还是每个月的最后一天都这样呢?
谢啦,谢啦

dhxwm5r4

dhxwm5r41#

你得到这个错误ValueError: day is out of range for month,因为最后一行建议int(datetime(today.year, today.month, today.day + 1, 0 , 0, 0).timestamp())),所以today.day + 1将是31+1 =32,(不是1月1日)这是一个无效的日期。为您想要的输出,你需要使用timedelta,为更具体的tomorrow = datetime.now() + timedelta(days=1)。你的最终代码将是:

from datetime import datetime, timedelta
from pytz import timezone
study_timezone = timezone('Europe/London')
today = study_timezone.localize(datetime.now())
tomorrow = datetime.now() + timedelta(days=1)

print("today",today)
print("Timestamp_Tomorrow: ", int(datetime(tomorrow.year, tomorrow.month, tomorrow.day, 0, 0, 0).timestamp()))

注意:您需要使用tomorrow.而不是today.方法。

相关问题