Python timezone '%z' directive for datetime.strptime() not available

后端 未结 3 1893
不思量自难忘°
不思量自难忘° 2020-12-01 09:35

Using \'%z\' pattern of datetime.strptime()

I have a string text that represent a date and I\'m perfectly able to parse it and transform it into a clean datetime o

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-01 10:06

    In continue to @j-f-sebastians 's answer, here is a fix for python 2.7

    Instead of using:

    datetime.strptime(t,'%Y-%m-%dT%H:%M %z')
    

    use the timedelta to account for the timezone, like this:

    from datetime import datetime,timedelta
    def dt_parse(t):
        ret = datetime.strptime(t[0:16],'%Y-%m-%dT%H:%M')
        if t[17]=='+':
           ret-=timedelta(hours=int(t[18:20]),minutes=int(t[20:]))
        elif t[17]=='-':
           ret+=timedelta(hours=int(t[18:20]),minutes=int(t[20:]))
        return ret
    
    print(dt_parse('2017-01-12T14:12 -0530'))
    

提交回复
热议问题