How can I convert a timestamp string with timezone offset to local time?

后端 未结 3 2189
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 18:00

I am trying to convert a string timestamp into a proper datetime object. The problem I am having is that there is a timezone offset and everything I am doing doesn\'t seem to wo

3条回答
  •  心在旅途
    2021-02-14 18:54

    It looks like datetime.datetime.strptime(d, '%a, %d %b %Y %H:%M:%S %z') should work, but according to this bug report there are issues with the %z processing. So you'll probably have to handle the timezone on your own:

    import datetime
    
    d = u"Fri, 16 Jul 2010 07:08:23 -0700"
    
    d, tz_info = d[:-5], d[-5:]
    neg, hours, minutes = tz_info[0], int(tz_info[1:3]), int(tz_info[3:])
    if neg == '-':
        hours, minutes = hours * -1, minutes * -1
    
    d = datetime.datetime.strptime(d, '%a, %d %b %Y %H:%M:%S ')
    print d
    print d + datetime.timedelta(hours = hours, minutes = minutes)
    

提交回复
热议问题