我有一个文本字符串,用空格分隔以下时间戳:
"""00:03:45.08 00:06:10.07 00:04:55.46 00:04:09.78 00:04:21.08 00:03:40.40 00:05:23.87 00:04:06.54 00:03:37.22 00:04:05.82 00:06:18.77 00:04:59.04 00:02:56.44 00:04:19.76 00:04:47.39 00:03:30.67 00:04:42.27 00:04:18.71 00:04:45.48 00:03:34.84 00:04:06.15 00:04:44,54 00:04:37.37 00:05:23.74 00:06:26,34 00:04:07.06 00:04:56.44"""
如何将字符串中的所有时间戳相加?
我认为输入数据是字符串,空格作为分隔符:
s = """00:03:45.08 00:06:10.07 00:04:55.46 00:04:09.78 00:04:21.08 00:03:40.40 00:05:23.87 00:04:06.54 00:03:37.22 00:04:05.82 00:06:18.77 00:04:59.04 00:02:56.44 00:04:19.76 00:04:47.39 00:03:30.67 00:04:42.27 00:04:18.71 00:04:45.48 00:03:34.84 00:04:06.15 00:04:44,54 00:04:37.37 00:05:23.74 00:06:26,34 00:04:07.06 00:04:56.44"""
这个代码是给你的:
import datetime
list_str = s.replace(',','.').split(" ")
list_date = map(lambda x: datetime.datetime.strptime(x, '%H:%M:%S.%f') - datetime.datetime(1900, 1, 1), list_str)
str(sum(list_date, datetime.timedelta(0)))
输出:
'2:02:50.330000'
使用以下一行可以得到相同的结果:
str(sum(map(lambda x: datetime.datetime.strptime(x, '%H:%M:%S.%f') - datetime.datetime(1900, 1, 1), s.replace(',','.').split(" ")),
datetime.timedelta(0)))
解释
首先,我们需要将输入字符串转换为字符串列表:
list_str = s.replace(',','.').split(" ")
使用datetime.datetime.strptime并减去库开始日期(1900-01-01(,将列表中的每个项目转换为datetime格式(python表示日期的格式(到格式'%H:%M:%S.%f'
。我使用映射功能将转换应用于整个列表:
list_date = map(lambda x: datetime.datetime.strptime(x, '%H:%M:%S.%f') - datetime.datetime(1900, 1, 1), list_str)
通过这种方式,我得到了datetime.timedelta元素的列表,我使用sum函数对其求和。我使用str((函数将结果转换为字符串格式:
str(sum(list_date, datetime.timedelta(0)))