How do I parse an ISO 8601-formatted date?

后端 未结 27 2308
小鲜肉
小鲜肉 2020-11-21 06:08

I need to parse RFC 3339 strings like \"2008-09-03T20:56:35.450686Z\" into Python\'s datetime type.

I have found strptime in the Python sta

相关标签:
27条回答
  • 2020-11-21 06:19

    An another way is to use specialized parser for ISO-8601 is to use isoparse function of dateutil parser:

    from dateutil import parser
    
    date = parser.isoparse("2008-09-03T20:56:35.450686+01:00")
    print(date)
    

    Output:

    2008-09-03 20:56:35.450686+01:00
    

    This function is also mentioned in the documentation for the standard Python function datetime.fromisoformat:

    A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil.

    0 讨论(0)
  • 2020-11-21 06:20

    New in Python 3.7+


    The datetime standard library introduced a function for inverting datetime.isoformat().

    classmethod datetime.fromisoformat(date_string):

    Return a datetime corresponding to a date_string in one of the formats emitted by date.isoformat() and datetime.isoformat().

    Specifically, this function supports strings in the format(s):

    YYYY-MM-DD[*HH[:MM[:SS[.mmm[mmm]]]][+HH:MM[:SS[.ffffff]]]]

    where * can match any single character.

    Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat().

    Example of use:

    from datetime import datetime
    
    date = datetime.fromisoformat('2017-01-01T12:30:59.000000')
    
    0 讨论(0)
  • 2020-11-21 06:20

    Starting from Python 3.7, strptime supports colon delimiters in UTC offsets (source). So you can then use:

    import datetime
    datetime.datetime.strptime('2018-01-31T09:24:31.488670+00:00', '%Y-%m-%dT%H:%M:%S.%f%z')
    

    EDIT:

    As pointed out by Martijn, if you created the datetime object using isoformat(), you can simply use datetime.fromisoformat()

    0 讨论(0)
  • 2020-11-21 06:21

    Note in Python 2.6+ and Py3K, the %f character catches microseconds.

    >>> datetime.datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")
    

    See issue here

    0 讨论(0)
  • 2020-11-21 06:21

    The python-dateutil will throw an exception if parsing invalid date strings, so you may want to catch the exception.

    from dateutil import parser
    ds = '2012-60-31'
    try:
      dt = parser.parse(ds)
    except ValueError, e:
      print '"%s" is an invalid date' % ds
    
    0 讨论(0)
  • 2020-11-21 06:22
    def parseISO8601DateTime(datetimeStr):
        import time
        from datetime import datetime, timedelta
    
        def log_date_string(when):
            gmt = time.gmtime(when)
            if time.daylight and gmt[8]:
                tz = time.altzone
            else:
                tz = time.timezone
            if tz > 0:
                neg = 1
            else:
                neg = 0
                tz = -tz
            h, rem = divmod(tz, 3600)
            m, rem = divmod(rem, 60)
            if neg:
                offset = '-%02d%02d' % (h, m)
            else:
                offset = '+%02d%02d' % (h, m)
    
            return time.strftime('%d/%b/%Y:%H:%M:%S ', gmt) + offset
    
        dt = datetime.strptime(datetimeStr, '%Y-%m-%dT%H:%M:%S.%fZ')
        timestamp = dt.timestamp()
        return dt + timedelta(hours=dt.hour-time.gmtime(timestamp).tm_hour)
    

    Note that we should look if the string doesn't ends with Z, we could parse using %z.

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