如何在python中将小时添加到当前时间 [英] How to add hours to current time in python
本文介绍了如何在python中将小时添加到当前时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我能够得到如下所示的当前时间:
I am able to get the current time as below:
from datetime import datetime
str(datetime.now())[11:19]
结果
Result
'19:43:20'
现在,我想在上述时间中添加 9小时
,如何在Python中为当前时间添加小时?
Now, i am trying to add 9 hours
to the above time, how can I add hours to current time in Python?
推荐答案
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'
或者,如@eumiro在评论中指出的- strftime
Or, as @eumiro has pointed out in comments - strftime
这篇关于如何在python中将小时添加到当前时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文