将类型为“hh.mm.ss.ms”的timedelta添加到datetime对象

时间:2013-10-07 21:05:21

标签: python datetime timedelta

我有一个类似于以下"0:07:38.701"的字符串,表示0小时,7分钟,38秒和701毫秒。

然后我有一个datetime对象,如下所示:datetime.datetime(1945, 1, 3, 11, 45, 0, 44000)

我想添加这些时间(第一个是delta,而第二个是绝对时间参考)并获得一个新的datetime.datetime对象。

我该怎么做?

4 个答案:

答案 0 :(得分:2)

获得datetimetimedelta后,添加它们就像使用+运算符一样简单:

>>> dt = datetime.datetime(1945, 1, 3, 11, 45, 0, 44000)
>>> td = datetime.timedelta(hours=0, minutes=7, seconds=38.701)
>>> dt + td
datetime.datetime(1945, 1, 3, 11, 52, 38, 745000)

对于timedelta对象,strptime对象没有内置解析器,类似于datetime

你有时可以通过将字符串解析为datetime来伪造它,然后提取字段以构建timedelta,但这既麻烦又复杂 - 对于简单的格式,你可以写一个简单的:

def strpdelta(s):
    hr, min, sec = map(float, s.split(':'))
    return datetime.timedelta(hours=hr, minutes=min, seconds=sec)

答案 1 :(得分:1)

您可以使用time delta

>>> import datetime, re
>>> s = "0:07:38.701"
>>> hours, minutes, seconds = [float(val) for val in s.split(':')]
>>> delta = datetime.timedelta(hours=hours, minutes=minutes, seconds=seconds)
>>> datetime.datetime(1945, 1, 3, 11, 45, 0, 44000) + delta
datetime.datetime(1945, 1, 3, 11, 52, 38, 745000)

答案 2 :(得分:1)

编辑:正如评论中所指出的,timedelta可以处理浮动值。即如果seconds=38.701,它会将其转换为secondsmilliseconds

from datetime import timedelta, datetime

dtime = datetime(1945, 1, 3, 11, 45, 0, 44000)
str = "0:07:38.701"

elems = str.split(':')
hr, min, sec= int(elems[0]), int(elems[1]), float(elems[2])

tdelta = timedelta(hours=hr, minutes=min, seconds=sec)

new_datetime = dtime + tdelta

编辑前的版本:

from datetime import timedelta, datetime

dtime = datetime(1945, 1, 3, 11, 45, 0, 44000)
str = "0:07:38.701"

stuff = str.split(':')
elems = stuff[:-1] + stuff[2].split('.')
hr, min, sec, mls= int(elems[0]), int(elems[1]), int(elems[2], int(elems[3]))

tdelta = timedelta(hours=hr, minutes=min, seconds=sec, milliseconds=mls)

new_datetime = dtime + tdelta

答案 3 :(得分:1)

另一个解决方案,也是我最喜欢的解决方案,因为它不需要手动解析,并使用datetime中的现有功能来解析字符串格式的日期:

# Input times:
init_time       =  datetime.datetime(1945, 1, 3, 11, 45, 0, 44000)
time_to_add_str = '0:00:05.00'

# Adding them up:
time_to_add = datetime.strptime(time_to_add_str, '%H:%M:%S.%f') - datetime(1900,1,1)
final_time  = time_to_add  + init_time