How do I parse an ISO 8601-formatted date?

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

    If you don't want to use dateutil, you can try this function:

    def from_utc(utcTime,fmt="%Y-%m-%dT%H:%M:%S.%fZ"):
        """
        Convert UTC time string to time.struct_time
        """
        # change datetime.datetime to time, return time.struct_time type
        return datetime.datetime.strptime(utcTime, fmt)
    

    Test:

    from_utc("2007-03-04T21:08:12.123Z")
    

    Result:

    datetime.datetime(2007, 3, 4, 21, 8, 12, 123000)
    

提交回复
热议问题