Python - 如何检查 UTC 日期字符串是否正确?

Python - How can I check if a UTC date string is correct?

我在 POST 请求中收到一个日期值,它的格式为 20220509T000000Z

在我工作的系统中,有时用户会发送错误的日期值,例如 2022059T000000Z2022509T000000Z。该日期在我们的数据库中保存为字符串,但如果它不正确,我们稍后会在进行一些计算和显示信息时遇到问题。

所以,我正在 Python 中寻找一种方法来验证字符串是否为正确的日期格式,如下所示:

#parameter date is the string I receive on the POST
def validate(date):
    if date is valid:
        # a valid date would be 20220509T000000Z
        return true
    else:
        # an incorrect date would be 2022509T000000Z
        return 'Error, incorrect date values'

提前致谢

一种方法是尝试使用 dateutil 解析器并排除:

import dateutil

#parameter date is the string I receive on the POST
def validate(date):
    try:
        dateutil.parser.parse(date)
        # a valid date would be 20220509T000000Z
        return True
    except Exception as e:
        # an incorrect date would be 2022509T000000Z
        return 'Error, incorrect date values'