How do I parse an ISO 8601-formatted date?

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

    A simple option from one of the comments: replace 'Z' with '+00:00' - and use Python3.7+'s fromisoformat.

    from datetime import datetime
    
    s = "2008-09-03T20:56:35.450686Z"
    
    datetime.fromisoformat(s.replace('Z', '+00:00'))
    # datetime.datetime(2008, 9, 3, 20, 56, 35, 450686, tzinfo=datetime.timezone.utc)
    

    Although strptime can parse the 'Z' character, fromisoformat is faster by ~ x40 (see also: A faster strptime):

    %timeit datetime.fromisoformat(s.replace('Z', '+00:00'))
    387 ns ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    %timeit datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')
    15.3 µs ± 540 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    

提交回复
热议问题