代码之家  ›  专栏  ›  技术社区  ›  curlyreggie

将基于GMT的时间转换为UTC python

  •  1
  • curlyreggie  · 技术社区  · 11 年前

    我有个约会 2014/08/19 03:38:46 GMT-4 从数据库中删除。

    如何在Python中将其转换为UTC格式的日期?

    PS:我使用Python 2.6.6

    2 回复  |  直到 11 年前
        1
  •  4
  •   xecgr    11 年前

    拥有一个非天真的datetime对象,您只应该调用 astimezone 具有所需时区的方法

    >>> import pytz
    >>> from dateutil import parser
    # dateutil.parser get a datetime object from string, we ensure that is a non-naive datetime
    >>> parser.parse('2014/08/19 03:38:46 GMT-4')
    datetime.datetime(2014, 8, 19, 3, 38, 46, tzinfo=tzoffset(None, 14400))
    >>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
    >>> dt.astimezone (pytz.utc)
    datetime.datetime(2014, 8, 18, 23, 38, 46, tzinfo=<UTC>)
    

    你的评论是对的,utc时间应该落后,所以尽管我认为另一个解决方案,但这个呢

    >>> dt = parser.parse('2014/08/19 03:38:46 GMT-4')
    >>> dt.replace(tzinfo=pytz.utc) + dt.tzinfo._offset
    datetime.datetime(2014, 8, 19, 7, 38, 46, tzinfo=<UTC>)
    
        2
  •  1
  •   Community CDub    8 年前

    GMT-4 模棱两可:现在是美国的时候了吗( -0400 utc偏置)或欧洲/莫斯科( +0400 )?

    $ TZ=GMT-4 date +%Z%z
    GMT+0400
    $ TZ=UTC-4 date +%Z%z
    UTC+0400
    $ TZ=America/New_York date +%Z%z
    EDT-0400
    $ TZ=Europe/Moscow date +%Z%z
    MSK+0400
    

    Your comment suggests 你需要反转utc偏移的符号。

    Python 2.6在stdlib中没有固定的偏移时区。你可以使用 the example implementation from the datetime docs :

    from datetime import tzinfo, timedelta, datetime
    
    ZERO = timedelta(0)
    
    class FixedOffset(tzinfo):
        """Fixed UTC offset: `local = utc + offset`."""
    
        def __init__(self, offset, name):
            self.__offset = timedelta(hours=offset)
            self.__name = name
    
        def utcoffset(self, dt):
            return self.__offset
    
        def tzname(self, dt):
            return self.__name
    
        def dst(self, dt):
            return ZERO
    
    utc = FixedOffset(0, "UTC")
    

    然后,要解析时间字符串,可以使用 strptime() :

    dt = datetime.strptime("2014/08/19 03:38:46 GMT-4", "%Y/%m/%d %H:%M:%S GMT-4")
    aware = dt.replace(tzinfo=FixedOffset(-4, "GMT-4"))
    print(aware)                 # -> 2014-08-19 03:38:46-04:00
    print(aware.astimezone(utc)) # -> 2014-08-19 07:38:46+00:00