我尝试了不同的正则表达式来匹配yyyymmddsssss,但没有任何效果。你能告诉我如何匹配" yyyymmddsssss" python正则表达式中的格式?
Ex: 2017122512345
2017 - year
12 - month
25 - day of month
12345 - milliseconds
答案 0 :(得分:4)
Why go the regular expression route for this kind of a problem?
Easier to ask for forgiveness - 尝试加载datetime.strptime()
并处理可能的ValueError
- %Y%m%d%f
格式应该是您正在寻找的内容:
In [1]: from datetime import datetime
In [2]: def validate(date_string):
try:
datetime.strptime(date_string, '%Y%m%d%f')
print('Valid')
except ValueError:
print('Invalid')
In [3]: validate('2017122512345')
Valid
In [4]: validate('20171')
Invalid
In [5]: validate('illegal')
Invalid