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

后端 未结 3 1866
不思量自难忘°
不思量自难忘° 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:18

    The Answer of Uri is great, saved my life, but when you have USE_TZ = True you need to be careful with the time, for avoid the warning "RuntimeWarning: DateTimeField" is better if you add the utc to the return.

    import pytz
    from datetime import datetime, timedelta
    def dt_parse(t):
        ret = datetime.strptime(t[0:19],'%Y-%m-%dT%H:%M:%S')
        if t[23]=='+':
            ret-=timedelta(hours=int(t[24:26]), minutes=int(t[27:]))
        elif t[23]=='-':
            ret+=timedelta(hours=int(t[24:26]), minutes=int(t[27:]))
        return ret.replace(tzinfo=pytz.UTC)
    

提交回复
热议问题