Convert JSON date string to Python datetime

后端 未结 2 1979
走了就别回头了
走了就别回头了 2020-12-08 13:14

When translating dates to JSON, javascript is saving dates in this format:

2012-05-29T19:30:03.283Z

However, I am not sure how to get this

相关标签:
2条回答
  • 2020-12-08 13:45

    To provide an alternative, if you don't mind installing the python-dateutil package, you can use dateutil.parser.parse. Be advised that the format of the input is guessed by parse; an invalid input can still be interpreted, correctly or otherwise.

    Without timezone

    If you would rather not have the time zone set, which is perfectly fine if you represent all times internally as UTC only, use:

    >>> dateutil.parser.parse('2012-05-29T19:30:03.283Z', ignoretz=True)
    datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)
    

    With timezone

    Note that unlike datetime.datetime.strptime, this default call to parse automatically preserves the UTC time zone.

    >>> import dateutil.parser
    >>> dateutil.parser.parse('2012-05-29T19:30:03.283Z')
    datetime.datetime(2012, 5, 29, 19, 30, 3, 283000, tzinfo=tzutc())
    

    If a test assertion for equality needs to be made, the expected object can be constructed as:

    >>> import datetime
    >>> datetime.datetime(2012, 5, 29, 19, 30, 3, 283000, tzinfo=dateutil.tz.tzutc())
    
    0 讨论(0)
  • 2020-12-08 14:00

    Try the following format:

    %Y-%m-%dT%H:%M:%S.%fZ
    

    For example:

    >>> datetime.datetime.strptime('2012-05-29T19:30:03.283Z', '%Y-%m-%dT%H:%M:%S.%fZ')
    datetime.datetime(2012, 5, 29, 19, 30, 3, 283000)
    

    The Z in the date just means that it should be interpreted as a UTC time, so ignoring it won't cause any loss of information. You can find this information here: http://www.w3.org/TR/NOTE-datetime

    0 讨论(0)
提交回复
热议问题