使用timedelta计算两个ISO8601时间之间的delta

Using timedelta to calculate delta between two ISO8601 times

我正在尝试计算两个 ISO8601 格式时间之间的差值。我有兴趣维护时间标准中的 6 位有效数字。我发现了 "timedelta" 功能,但无法使其正常工作。

a = datetime.datetime.strptime('2018-05-09T18:28:55.251537', '%Y-%m-%dT%H:%M:%S.%f%f%f%f%f%f')
b = datetime.datetime.strptime('2018-05-09T18:51:55.251537', '%Y-%m-%dT%H:%M:%S.%f%f%f%f%f%f')

关于如何计算这两个时间之间精确到毫秒的差异有什么想法吗?

编辑: 我的实际代码如下:

command = "NAME,COMMAND,2018-05-10T18:31:30.515276"
command_lis = command.replace("/n"," ").split(",")
print("Received the following time: " + command_lis[2])
a = datetime.datetime.strptime(datetime.datetime.utcnow().isoformat(), '%Y-%m-%dT%H:%M:%S.%f')
print("a is set")
b = datetime.datetime.strptime(command_lis[2], '%Y-%m-%dT%H:%M:%S.%f')
print("b is set")
delta = b - a
print(delta)

作为答案发布(至少是暂时的)因为我需要代码格式化的空间。如果我 运行 您在 python 终端中提供的代码,一切似乎都按预期工作:

% python
Python 2.7.8 (default, Apr 25 2018, 00:29:19) 
[GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> command = "NAME,COMMAND,2018-05-10T18:31:30.515276"
>>> command_lis = command.replace("/n"," ").split(",")
>>> print("Received the following time: " + command_lis[2])
Received the following time: 2018-05-10T18:31:30.515276
>>> a = datetime.datetime.strptime(datetime.datetime.utcnow().isoformat(), '%Y-%m-%dT%H:%M:%S.%f')
>>> print("a is set")
a is set
>>> b = datetime.datetime.strptime(command_lis[2], '%Y-%m-%dT%H:%M:%S.%f')
>>> print("b is set")
b is set
>>> delta = b - a
>>> print(delta)
-5 days, 18:25:54.502559

你有不同的行为吗?