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

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

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

结果

'19:43:20'

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

最佳答案

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

https://stackoverflow.com/questions/13685201/

相关文章:

python - 如何使用 conda 升级到 Python 3.6?

python - 在 Python 中找到 "home directory"?

python - 等到页面用 Selenium WebDriver for Python 加载

linux - rm : cannot remove: Permission denied

python - 使用 Python 遍历目录

linux - 使用 sed 删除 Linux 中文本文件任意行的前五个字符

mysql - 如何重启在 Ubuntu linux 上运行的远程 MySQL 服务器?

python - 将 float 转换为一定精度,然后复制为字符串

python - 如何创建键或将元素附加到键?

c++ - 您使用什么工具在 Linux 上开发 C++ 应用程序?