python时间偏移

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14043934/
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 10:15:26  来源:igfitidea点击:

python time offset

pythontime

提问by Guillaume07

How can I apply an offset on the current time in python?

如何在python中的当前时间应用偏移量?

In other terms, be able to get the current time minus x hours and/or minus m minutes and/or minus s secondes and/or minus ms milliseconds

换句话说,能够得到当前时间减去 x 小时和/或减去 m 分钟和/或减去 s 秒和/或减去 ms 毫秒

for instance

例如

curent time = 18:26:00.000

offset = 01:10:00.000

=>resulting time = 17:16:00.000

采纳答案by Martijn Pieters

Use a datetime.datetime(), then add or subtract datetime.timedelta()instances.

使用 a datetime.datetime(),然后添加或减去datetime.timedelta()实例

>>> import datetime
>>> t = datetime.datetime.now()
>>> t - datetime.timedelta(hours=1, minutes=10)
datetime.datetime(2012, 12, 26, 17, 18, 52, 167840)

timedelta()arithmetic is not supported for datetime.time()objects; if you need to use offsets from an existing datetime.time()object, just use datetime.datetime.combine()to form a datetime.datetime()instance, do your calculations, and 'extract' the time again with the .time()method:

timedelta()datetime.time()对象不支持算术;如果您需要使用现有datetime.time()对象的偏移量,只需用于datetime.datetime.combine()形成一个datetime.datetime()实例,进行计算,然后使用该.time()方法再次“提取”时间:

>>> t = datetime.time(1, 2)
>>> dt = datetime.datetime.combine(datetime.date.today(), t)
>>> dt
datetime.datetime(2012, 12, 26, 1, 2)
>>> dt -= datetime.timedelta(hours=5)
>>> dt.time()
datetime.time(20, 2)