How do I parse an ISO 8601-formatted date?

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

    What is the exact error you get? Is it like the following?

    >>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
    ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z
    

    If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.

    Try this:

    >>> def gt(dt_str):
            dt, _, us= dt_str.partition(".")
            dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
            us= int(us.rstrip("Z"), 10)
            return dt + datetime.timedelta(microseconds=us)
    
    >>> gt("2008-08-12T12:20:30.656234Z")
    datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)
    

提交回复
热议问题