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:
这里不需要Regex,这是可能的,但是使用
datetime
更容易:输出:
我建议避免使用正则表达式从字符串中提取日期。如果已知可能的格式数,那么只需尝试转换为
datetime
对象。如果转换失败,请尝试下一种可能的格式。你知道吗例如:
这样做的好处是可以跳过非法日期,比如
2018-09-31
,并且可以正确处理闰年。它也更容易遵循。你知道吗相关问题 更多 >
编程相关推荐