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

后端 未结 3 1786
不思量自难忘°
不思量自难忘° 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'))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-01 10:23

    strptime() is implemented in pure Python. Unlike strftime(); it [which directives are supported] doesn't depend on platform. %z is supported since Python 3.2:

    >>> from datetime import datetime
    >>> datetime.strptime('24/Aug/2014:17:57:26 +0200', '%d/%b/%Y:%H:%M:%S %z')
    datetime.datetime(2014, 8, 24, 17, 57, 26, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
    

    how to parse Email time zone indicator using strptime() without being aware of locale time?

    There is no concrete timezone implementation in Python 2.7. You could easily implement the UTC offset parsing, see How to parse dates with -0400 timezone string in python?

    0 讨论(0)
提交回复
热议问题