我正在使用从mongoDB检索到的日期,但是,它们的格式都不相同。它们有3种不同的格式:
1. '%H:%M:%S' (Hours:Minutes:Seconds)
2. '%H:%M:%S.f' (Hours:Minutes:Seconds:Milliseconds)
3. Days.Hours:Minutes:Seconds:Milliseconds
我想计算数据库中所有记录的总时间。日期以字符串格式存储,因此我正在使用strptime函数检索时间对象,然后使用该时间对象创建一个timedelta,以便我可以将其全部添加:
formats = ('%H:%M:%S', '%%H:%M:%S.f', <3rd format here>)
for db_item in db_collection:
for fmt in formats:
try:
temp = datetime.strptime(db_item, fmt)
temp = datetime.timedelta(hours=temp.hour,
minutes=temp.minute,
seconds=temp.minute,
milliseconds=(temp.microsecond / 1000)
return temp
except ValueError as e:
但是问题是我前面提到的第三种格式指定了'。'之前的n天,因此我不知道如何为这种格式编写日期格式字符串。
示例
1.01:20:40.97
表示:1天(24小时),1小时,20分钟,40秒和97毫秒
我的目标是:25:20:40.97(24小时+1小时)
是否有允许使用此格式的格式?还是我应该分别提取n天,乘以24,然后在以后手动添加?
您可以尝试%d
格式代码。但是,您会遇到限制,因为%d
是每月的一天,这意味着它是range(1,31 + 1)之内的整数。datetime.datetime专门用于日期和时间,而不是持续时间。
使用正则表达式解析字符串并直接构造timedelta然后使用%d
格式代码可能更容易。
这里是一个正则表达式,适用于所有三种持续时间格式。
import re
pattern = re.compile(
"""
# 0? to remove leading zero
# days and milliseconds are optional
(?: (\d+). )? # days
0? (\d+): # hours
0? (\d+): # minutes
0? (\d+) # seconds
(?: . (\d+))? # milliseconds
""",
re.VERBOSE
)
match = pattern.fullmatch("01:20:40")
if match is not None: # if fullmatch fails match is None
print(match.groups())
match = pattern.fullmatch("01:20:40.97")
if match is not None:
print(match.groups())
match = pattern.fullmatch("1.01:20:40.97")
if match is not None:
print(match.groups())
输出
(None, '1', '20', '40', None)
(None, '1', '20', '40', '97')
('1', '1', '20', '40', '97')