如何在Python验证期间要求将时间戳记零填充? [英] How to require a timestamp to be zero-padded during validation in Python?

查看:60
本文介绍了如何在Python验证期间要求将时间戳记零填充?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证应该包含 ISO 8601格式的时间戳的字符串.a>(通常在JSON中使用).

I'm trying to validate a string that's supposed to contain a timestamp in the format of ISO 8601 (commonly used in JSON).

Python的 strptime 似乎非常宽容,请参见下面的代码示例(请注意,小时缺少前导零):

Python's strptime seems to be very forgiving when it comes to validating zero-padding, see code example below (note that the hour is missing a leading zero):

>>> import datetime
>>> s = '1985-08-23T3:00:00.000'
>>> datetime.datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f')
datetime.datetime(1985, 8, 23, 3, 0)

例如,它优雅地接受一个小时未填充零的字符串,并且不会像我期望的那样抛出 ValueError 异常.

It gracefully accepts a string that's not zero-padded for the hour for example, and doesn't throw a ValueError exception as I would expect.

是否有任何方法可以强制strptime验证其是否为零填充?还是Python的标准库中有其他内置函数呢?

Is there any way to enforce strptime to validate that it's zero-padded? Or is there any other built-in function in the standard libs of Python that does?

我想避免为此编写自己的 regexp .

I would like to avoid writing my own regexp for this.

推荐答案

已经有一个答案,即无法使用Python strptime()解析ISO8601或RFC3339日期/时间:

There is already an answer that parsing ISO8601 or RFC3339 date/time with Python strptime() is impossible: How to parse an ISO 8601-formatted date? So, to answer you question, no there is no way in the standard Python library to reliable parse such a date. Regarding the regex suggestions, a date string like

2020-14-32T45:33:44.123

将导致有效日期.Python模块很多(如果您在 https://pypi.python.org 上搜索"iso8601"),但是构建 complete ISO8601验证程序将需要诸如leap秒,可能的时区偏移值列表等更多内容.

would result in a valid date. There are lots of Python modules (if you search for "iso8601" on https://pypi.python.org), but building a complete ISO8601 Validator would require things like leap seconds, the list of possible time zone offset values and many more.

这篇关于如何在Python验证期间要求将时间戳记零填充?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆