如何在python中将小时添加到当前时间

问题:如何在python中将小时添加到当前时间

我可以得到如下的当前时间:

from datetime import datetime
str(datetime.now())[11:19]

结果

'19:43:20'

现在,我正在尝试增加9 hours上述时间,如何在Python中为当前时间增加几个小时?

I am able to get the current time as below:

from datetime import datetime
str(datetime.now())[11:19]

Result

'19:43:20'

Now, i am trying to add 9 hours to the above time, how can I add hours to current time in Python?


回答 0

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

然后使用字符串格式获取相关内容:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

如果仅格式化日期时间,则可以使用:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

或者,正如@eumiro在评论中指出的那样- strftime

from datetime import datetime, timedelta

nine_hours_from_now = datetime.now() + timedelta(hours=9)
#datetime.datetime(2012, 12, 3, 23, 24, 31, 774118)

And then use string formatting to get the relevant pieces:

>>> '{:%H:%M:%S}'.format(nine_hours_from_now)
'23:24:31'

If you’re only formatting the datetime then you can use:

>>> format(nine_hours_from_now, '%H:%M:%S')
'23:24:31'

Or, as @eumiro has pointed out in comments – strftime


回答 1

导入日期时间和时间增量

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

但是更好的方法是:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

您可以通过引用strptimestrftime行为来更好地了解python如何处理日期和时间字段

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field