格式 HH:MM:SS.MICROSECOND 的日期时间 strptime 方法

datetime strptime method for format HH:MM:SS.MICROSECOND

我正在尝试研究 Python 时间条带时间方法来分解表示为 11:49:57.74 的时间。标准的%H、%M、%S可以分解时、分、秒。但是,由于数据是一个字符串(在 python pandas 列中作为数据类型对象,小数点后的毫秒数未被解释。因此,我得到一个错误。有人可以告诉我如何解析示例以便从时间字符串中正确解释秒和微秒? 然后我会用它们来找到两个时间戳之间的时间差。

不知道我是否理解正确你的问题。

因此,要将该字符串时间转换为日期时间并计算两次之间的时间增量,您需要执行以下操作:

timedelta = str() #declare an empty string where save the timedelta

my_string = '11:49:57.74' # first example time
another_example_time = '13:49:57.74' #second example time, invented by me for the example

first_time = datetime.strptime(my_string, "%H:%M:%S.%f") # extract the first time
second_time = datetime.strptime(another_example_time , "%H:%M:%S.%f") # extract the second time

#calculate the time delta
if(first_time > second_time):
    timedelta = first_time - second_time 
else:
    timedelta = second_time - first_time

print "The timedelta between %s and %s is: %s" % (first_time, second_time, timedelta)

这里很明显你没有任何日期,所以日期时间库默认使用 1900-01-01 正如你在打印结果中看到的那样:

The timedelta between 1900-01-01 11:49:57.740000 and 1900-01-01 13:49:57.740000 is: 2:00:00

我希望这个解决方案是您所需要的。下次请提供更多信息,或分享您尝试编写的代码示例。