2 回答
TA贡献1830条经验 获得超9个赞
如果格式保持简单:<digits> <unit> ago ...用"^(\d+) (\w+) ago".
然后,一旦你('minutes', '12')将这些传递给timedelta它接受每个单元作为关键字参数timedelta(minutes=12),你将通过传递一个映射来做到这一点**{unit:value}
def parse(content):
timeparts = re.search(r"^(\d+) (\w+) ago", content)
if not timeparts:
return None, content
unit = timeparts.group(2).rstrip('s') + 's' # ensure ends with 's'
#return datetime.now()-timedelta(**{unit:int(timeparts.group(1))}) # Now date
return datetime(2020,5,26,8,0,0)-timedelta(**{unit:int(timeparts.group(1))}) # Fixed date
演示
values = ["12 minutes ago - There was a meeting...","2 hours ago - Apologies for being...","1 day ago - It is a sunny day in London..."]
for value in values:
res = parse(value)
print(res)
2020-05-26 07:48:00
2020-05-26 06:00:00
2020-05-25 08:00:00
添加回答
举报