Check if datetime string is in ISO 8601 format
Asked Answered
W

1

7

I like to parse datetime strings with dateutil.parser.parse module. It's simple. However I noticed in my code that I have to check if the object is indeed in 8601 (and aware).

My structure is:

if parse(datetime).tzinfo==None:
   #do something
else:
   #make it aware
   #do something

and I want to achieve something like:

if <IS-8601>:
   if parse(datetime).tzinfo==None:
      #do something
   else:
      #make it aware
      #do something
else:
   pass

If I have a 8601 like e.g. 2014-02-28T22:30:00+0200 parse utility does its job.

If I have however a 2014-03-20 string parse will add time on the object. That's not wrong, just unwanted: 2014-03-20 00:00:00


So how can I check if an object is in 8601? And if in 8601, is it aware? I don't mind change to another datetime library.

Whitaker answered 3/3, 2014 at 6:59 Comment(2)
U can use regular expression . re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$')Menorrhagia
ISO 8601 can have timezone character at end, i.e. Z instead of offset and can also have milliseconds.Urmia
R
1

You can parse it by datetime module and check for exception ValueError before processing by dateutil.parser.parse :

>>> import datetime
>>> datetime.datetime.strptime("2014-03-20", '%Y-%m-%d')
datetime.datetime(2014, 3, 20, 0, 0)
>>> datetime.datetime.strptime("2014-02-28T22:30:00+0200", '%Y-%m-%d')
Traceback (most recent call last):
  File "<pyshell#134>", line 1, in <module>
    datetime.datetime.strptime("2014-02-28T22:30:00+0200", '%Y-%m-%d')
  File "C:\Python33\lib\_strptime.py", line 500, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "C:\Python33\lib\_strptime.py", line 340, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: T22:30:00+0200
Ramon answered 3/3, 2014 at 7:12 Comment(1)
This parser can parse much more than ISO8601-compliant strings, so it's not a good way of validating ISO8601 compliance.Sharma

© 2022 - 2024 — McMap. All rights reserved.