I'm writing an API and I would like to accept ISO 8601 format for date and time. I want to accept only that format. I'm using dateutil
at the moment, but its parse function accepts all manner of formats unrelated to ISO8601. I have a simple regex checking the format now, but the actual standard allows a lot more than what my regex does.
Is there a simple function/module which provides a way to parse only 8601 formatted dates/times?
You can use datetime.datetime.strptime
, which will give an error if it cannot parse against the format you specify:
from datetime import datetime
def parse_8601(s):
"""Parses date string if in an ISO 8601 format, else returns None."""
for f in ["%Y-%m-%dT%H:%M:%S", ...]: # acceptable formats
try:
return datetime.strptime(s, f)
except ValueError:
pass
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.