Parsing dates
When receiving a datetime from another software or from a user, it will probably be in a string format. Formats such as JSON don't even define how a date should be represented, but it's usually a best practice to provide those in the ISO 8601 format.
The ISO 8601 format is usually defined as [YYYY]-[MM]-[DD]T[hh]:[mm]:[ss]+-[TZ]
, for example 2018-03-19T22:00+0100
would refer to March 19 at 10 P.M. on the UTC+01:00 time zone.
ISO 8601 conveys all the information you need to represent a date and time, so it's a good way to marshal a datetime and send it across a network.
Sadly, it has many oddities (for example, the +00
time zone can also be written as Z
, or you can omit the :
between hours, minutes, and seconds), so parsing it might sometimes cause trouble.
How to do it...
Here are the steps to follow:
- Due to all the variants ISO 8601 allows, there is no easy way to throw it to
datetime.datetime.strptime
and get back a datetime for all case; we must coalesce all possible formats to...