2016-03-18 130 views
8

我想计算从现在到明天12:00之间的秒数。所以我需要明天12:00 datetime对象。如何在Python中修改datetime.datetime.hour?

这是伪代码:

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:00 datetime对象?

+0

你可以看看[这个答案] HTTP ://stackoverflow.com/questions/8777753/converting-datetime-date-to-utc-timestamp-in-python)所以你可以转换**明天12:00 ** datetime到时间戳,然后减去'time.time( )' – pixis

回答

18

使用replace 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.

2

试试这个:

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