如何在Python中修改datetime.datetime.hour?
我想计算一下从现在到明天12:00之间的秒数。所以我需要明天12:00获取日期时间对象 这是伪代码:如何在Python中修改datetime.datetime.hour?,python,datetime,Python,Datetime,我想计算一下从现在到明天12:00之间的秒数。所以我需要明天12:00获取日期时间对象 这是伪代码: today_time = datetime.datetime.now() tomorrow = today_time + datetime.timedelta(days = 1) tomorrow.hour = 12 result = (tomorrow-today_time).total_seconds() 但它会引发这样的错误: AttributeError: attribute 'hou
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
对象 试试这个:
tomorrow = datetime.datetime(tomorrow.year, tomorrow.month, tomorrow.day, 12, 0, 0)
使用可基于现有对象生成新的datetime
对象:
tomorrow = tomorrow.replace(hour=12)
返回具有相同属性的datetime,除了那些通过指定的关键字参数赋予新值的属性。请注意,可以指定tzinfo=None
,以从感知的日期时间创建原始日期时间,而不转换日期和时间数据
您可以查看一下,这样就可以将明天12:00的datetime转换为时间戳,然后减去time.time()