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

问题描述 投票:1回答:1

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

python-2.7 timestamp strptime
1个回答
1
投票

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

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

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)

这里显然你没有任何日期,所以datetime库默认使用1900-01-01,你可以在print的结果中看到:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.