Search code examples
pythondatetimeiso8601

ISO8601 format support in python datetime module


I have read so many questions on parsing ISO8601 in python but most of them use external dependencies. Then i bumped in to this question,

How to parse an ISO 8601-formatted date?

It explains that python doesn't support iso8601 formatting, but the answer is 3 years old.

I need to parse this date without using any external dependencies,

from datetime import datetime
app_login = "1996-12-19T16:39:57+08:00"
parse_app_login = datetime.strptime(x,"%Y-%m-%dT%H:%M:%S%z")
print(parse_app_login)

I get error:

ValueError: time data '1996-12-19T16:39:57+08:00' does not match format '%Y-%m-%dT%H:%M:%S%z'

i want to know why python does not support iso8601 format?


Solution

  • Please note that Python 3.7 support ISO8601 UTC offsets format,

    From Docs,

    Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

    using Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47),

    >>> from datetime import datetime
    >>> x = "2018-10-18T16:39:57+08:00"
    >>> y = datetime.strptime(x,"%Y-%m-%dT%H:%M:%S%z")
    >>> print(y)
    

    Output,

    2018-10-18 16:39:57+08:00