How to parse dates with -0400 timezone string in Python?

后端 未结 6 1368

I have a date string of the form \'2009/05/13 19:19:30 -0400\'. It seems that previous versions of Python may have supported a %z format tag in strptime for the trailing tim

6条回答
  •  猫巷女王i
    2020-11-22 09:54

    Here is a fix of the "%z" issue for Python 2.7 and earlier

    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[18]=='+':
            ret-=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
        elif t[18]=='-':
            ret+=timedelta(hours=int(t[19:22]),minutes=int(t[23:]))
        return ret
    

    Note that the dates would be converted to GMT, which would allow doing date arithmetic without worrying about time zones.

提交回复
热议问题