如何在Python中修改datetime.datetime.hour?

2024-04-28 21:15:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我想计算一下从现在到明天12点之间的秒数。所以我需要明天12:00datetime获取对象。

这是伪代码:

today_time = datetime.datetime.now()
tomorrow = today_time + datetime.timedelta(days = 1)
tomorrow.hour = 12
result = (tomorrow-today_time).total_seconds()

但它会引起这个错误:

AttributeError: attribute 'hour' of 'datetime.datetime' objects is not writable

如何修改小时数或如何获取明日12:00datetime对象?


Tags: 对象代码todaydatetimetime错误resultdays
2条回答

试试这个:

tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)

使用^{} method基于现有对象生成新的datetime对象:

tomorrow = tomorrow.replace(hour=12)

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified. Note that tzinfo=None can be specified to create a naive datetime from an aware datetime with no conversion of date and time data.

相关问题 更多 >