datetime strptime方法,格式为HH:MM:SS.MICROSECOND

时间:2019-02-26 10:51:23

标签: python-2.7 timestamp strptime

我正在尝试研究Python time striptime方法以分解表示为11:49:57.74的时间。标准的%H,%M,%S能够分解小时,分钟,秒。但是,由于数据是字符串(在python pandas列中作为数据类型对象,所以小数秒后的毫秒数未解释。因此,我遇到了错误。有人可以建议如何解析示例,以便秒从时间字符串正确解释了毫秒和微秒? 然后,我将使用它们来查找两个时间戳之间的时间增量。

1 个答案:

答案 0 :(得分:1)

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

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

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

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