How to parse timezone with colon

后端 未结 3 1915
情歌与酒
情歌与酒 2021-01-03 18:07

Is there a way to parse timezone in \"+00:00\" format with datetime.strptime? For instance:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:4         


        
相关标签:
3条回答
  • 2021-01-03 18:34

    Adapted from a rejected edit:

    Python >= 3.7:

    from datetime import datetime
    d = "2019-12-25T23:59:59+00:00"
    print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))
    

    Changed in version 3.7: When the %z directive is provided to the strptime() method, the UTC offsets can have a colon as a separator between hours, minutes and seconds. For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'.

    https://docs.python.org/3.7/library/datetime.html

    Python <= 3.6

    There is no built-in way, but the best solution is:

    from datetime import datetime
    d = "2019-12-25T23:59:59+00:00"
    if ":" == d[-3]:
        d = d[:-3]+d[-2:]
    print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))
    

    Explanations: https://bugs.python.org/issue15873 https://bugs.python.org/msg169952

    0 讨论(0)
  • 2021-01-03 18:37

    Another solution is to use the dateutil library:

    from dateutil import parser
    
    mystr = '2015-04-30T23:59:59+00:00'
    
    x = parser.parse(mystr)
    
    # 2015-04-30 23:59:59+00:00
    
    0 讨论(0)
  • 2021-01-03 18:50

    Currently, there is no cure for this, and here is and explanation: https://bugs.python.org/issue15873 more precisely, here: https://bugs.python.org/msg169952 . But you can override this issue, this way:

    from datetime import datetime
    d = "2015-04-30T23:59:59+00:00"
    if ":" == d[-3:-2]:
        d = d[:-3]+d[-2:]
    print(datetime.strptime(d, "%Y-%m-%dT%H:%M:%S%z"))
    
    0 讨论(0)
提交回复
热议问题