How to parse ISO8601 datetime in Python
The easiest way to parse a ISO8601 timestamp like 2019-05-29T19:50:55.463+02:00
is to install the maya library using e.g.
sudo pip3 install maya
In case you still use Python2, use pip
instead of pip3
.
After installing maya, use it like this:
import maya
result = maya.parse('2019-05-29T19:50:55.463+02:00').datetime()
# Result is a standard datetime object!
print(result)
This will print
2019-05-29 17:50:55.463000+00:00
Notice how the original timestamp from timezone +02:00
is automatically converted to a UTC datetime
object.
maya can parse a lot of different formats e.g.
print(maya.parse('2019-05-29T19:50:55+02:00').datetime()) # No fractional seconds
print(maya.parse('2019-05-29T19:50:55').datetime()) # No timezone (UTC assumed)
print(maya.parse('2019-05-29 19:50:55').datetime()) # Not ISO8601
print(maya.parse('2019-05-29').datetime()) # 00:00:00 & UTC assumed