在Python中,我应该如何在不考虑顺序的情况下查找日期和时间?

2024-09-24 22:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

import re
exp1="2018-7-12 13:00:00"
exp2="13:00:00 2018-7-12"
reg= r'\d\d\d\d[./-](0?[1-9]|1[0-2])[./-](0?[1-9]|[12][0-9]|3[01]) (00|[0- 9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])'
compDate = re.search(reg,exp1)

我也尝试过前瞻表达式,但它们无法使它们工作。你知道吗

欢迎任何其他解决方案


Tags: importresearch表达式解决方案reg前瞻exp1
2条回答

这里不需要Regex,这是可能的,但是使用datetime更容易:

from datetime import datetime

l = ["2018-7-12 13:00:00", "13:00:00 2018-7-12"]
l2 = ["%Y-%m-%d %H:%M:%S", "%H:%M:%S %Y-%m-%d"]

print([str(datetime.strptime(x,y)) for x,y in zip(l,l2)])

输出:

['2018-07-12 13:00:00', '2018-07-12 13:00:00']

我建议避免使用正则表达式从字符串中提取日期。如果已知可能的格式数,那么只需尝试转换为datetime对象。如果转换失败,请尝试下一种可能的格式。你知道吗

例如:

from datetime import datetime

test_dates = ["2018-7-12 13:00:00", "13:00:00 2018-7-12"]
date_formats = ["%Y-%m-%d %H:%M:%S", "%H:%M:%S %Y-%m-%d"]

for date in test_dates:
    for date_format in date_formats:
        try:
            dt = datetime.strptime(date, date_format)
            print(dt)
        except ValueError as e:
            pass

这样做的好处是可以跳过非法日期,比如2018-09-31,并且可以正确处理闰年。它也更容易遵循。你知道吗

相关问题 更多 >