How do I parse an ISO 8601-formatted date?

后端 未结 27 3125
小鲜肉
小鲜肉 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: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.

提交回复
热议问题