Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if datetime string is in ISO 8601 format

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.

like image 475
Diolor Avatar asked Mar 03 '14 06:03

Diolor


People also ask

How do I convert datetime to ISO 8601?

toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss.

Is valid ISO date string?

Yes, it is valid. It's basically extended in terms of subsecond support, but that's allowed by the standard.

What time is it in ISO 8601?

UTC time in ISO-8601 is 08:26:38Z.

Is ISO 8601 always UTC?

Date.prototype.toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .


1 Answers

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
like image 112
Jiri Avatar answered Sep 28 '22 09:09

Jiri