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

后端 未结 3 2184
佛祖请我去吃肉
佛祖请我去吃肉 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

    Here's a stdlib solution:

    >>> from datetime import datetime
    >>> from email.utils import mktime_tz, parsedate_tz
    >>> datetime.fromtimestamp(mktime_tz(parsedate_tz(u"Fri, 16 Jul 2010 07:08:23 -0700")))
    datetime.datetime(2010, 7, 16, 16, 8, 23) # your local time may be different
    

    See also, Python: parsing date with timezone from an email.

    Note: fromtimestamp() may fail if the local timezone had different UTC offset in the past (2010) and if it does not use a historical timezone database on the given platform. To fix it, you could use tzlocal.get_localzone(), to get a pytz tzinfo object representing your local timezone. pytz provides access to the tz database in a portable manner:

    >>> timestamp = mktime_tz(parsedate_tz(u"Fri, 16 Jul 2010 07:08:23 -0700"))
    >>> import tzlocal # $ pip install tzlocal
    >>> str(datetime.fromtimestamp(timestamp, tzlocal.get_localzone()))
    '2010-07-16 16:08:23+02:00'
    

提交回复
热议问题