如何使用python正则表达式验证日期格式yyyymmddssss?

2024-09-30 16:31:44 发布

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

我尝试了不同的正则表达式来匹配yyyymmddsssss,但没有任何结果。你能告诉我如何匹配python正则表达式中的“yyyymmddsssss”格式吗?在

Ex: 2017122512345

2017 - year
12 - month
25 - day of month
12345 - milliseconds

Tags: of格式yearexdaymonthmillisecondsyyyymmddsssss
1条回答
网友
1楼 · 发布于 2024-09-30 16:31:44

Why go the regular expression route for this kind of a problem?

enter image description here

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

相关问题 更多 >