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.
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.
Yes, it is valid. It's basically extended in terms of subsecond support, but that's allowed by the standard.
UTC time in ISO-8601 is 08:26:38Z.
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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With