如何设置日期时间的UTC偏移量?

时间:2013-09-10 14:52:51

标签: python datetime timezone

我的基于Python的Web服务器需要使用客户端的时区执行一些日期操作,由UTC偏移量表示。如何使用指定的UTC偏移量作为时区来构造日期时间对象?

3 个答案:

答案 0 :(得分:15)

使用dateutil

>>> import datetime
>>> import dateutil.tz
>>> datetime.datetime(2013, 9, 11, 0, 17, tzinfo=dateutil.tz.tzoffset(None, 9*60*60))
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=tzoffset(None, 32400))
>>> datetime.datetime(2013, 9, 11, 0, 17, tzinfo=dateutil.tz.tzoffset('KST', 9*60*60))
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=tzoffset('KST', 32400))

>>> dateutil.parser.parse('2013/09/11 00:17 +0900')
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=tzoffset(None, 32400))

答案 1 :(得分:10)

顺便说一句,Python 3(自v3.2起)现在有一个timezone class来执行此操作:

from datetime import datetime, timezone, timedelta

# offset is in seconds
utc_offset = lambda offset: timezone(timedelta(seconds=offset))

datetime(*args, tzinfo=utc_offset(x))

但是,请注意,此类别的对象不能用于表示在一年中的不同日期使用不同偏移量或已对民用时间进行历史更改的位置中的时区信息。&#34 ;对于严格依赖UTC偏移的任何时区转换,通常都是如此。

答案 2 :(得分:6)

datetime module documentation包含一个代表固定偏移量的示例tzinfo类。

ZERO = timedelta(0)

# A class building tzinfo objects for fixed-offset time zones.
# Note that FixedOffset(0, "UTC") is a different way to build a
# UTC tzinfo object.

class FixedOffset(tzinfo):
    """Fixed offset in minutes east from UTC."""

    def __init__(self, offset, name):
        self.__offset = timedelta(minutes = offset)
        self.__name = name

    def utcoffset(self, dt):
        return self.__offset

    def tzname(self, dt):
        return self.__name

    def dst(self, dt):
        return ZERO

由于Python 3.2不再需要提供此代码,因为datetimedatetime.timezone包含在{{1}}模块中,应该使用它。

相关问题