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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13685201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:23:31  来源:igfitidea点击:

How to add hours to current time in python

pythontimeadd

提问by Shiva Krishna Bavandla

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 hoursto the above time, how can I add hours to current time in Python?

现在,我正在尝试添加9 hours到上述时间,如何在 Python 中将小时添加到当前时间?

回答by Jon Clements

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

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

回答by u1860929

Import datetimeand timedelta:

导入datetimetimedelta

>>> 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 strptimeand strftimebehaviorto better understand how python processes dates and time field

您可以参考strptimestrftime行为以更好地了解python如何处理日期和时间字段