我想计算从现在到明天12:00之间的秒数.所以我需要明天12:00 datetime对象.
这是伪代码:
today_time = datetime.datetime.now()
tomorrow = today_time + datetime.timedelta(days = 1)
tomorrow.hour = 12
result = (tomorrow-today_time).total_seconds()
Run Code Online (Sandbox Code Playgroud)
但它会引发这个错误:
AttributeError: attribute 'hour' of 'datetime.datetime' objects is not writable
Run Code Online (Sandbox Code Playgroud)
如何修改小时或如何获得明天的12:00 datetime对象?
Chr*_*ris 69
使用该replace方法datetime基于现有对象生成新对象:
tomorrow = tomorrow.replace(hour=12)
Run Code Online (Sandbox Code Playgroud)
返回具有相同属性的日期时间,但通过指定的任何关键字参数给定新值的属性除外.请注意,
tzinfo=None可以指定从感知日期时间创建天真日期时间而不转换日期和时间数据.
尝试这个:
tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)
Run Code Online (Sandbox Code Playgroud)