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

lai*_*ech 14 python timezone datetime

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

fal*_*tru 16

使用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))
Run Code Online (Sandbox Code Playgroud)
>>> dateutil.parser.parse('2013/09/11 00:17 +0900')
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=tzoffset(None, 32400))
Run Code Online (Sandbox Code Playgroud)


小智 11

顺便说一下,Python 3(自v3.2起)现在有一个时区类来执行此操作:

from datetime import datetime, timezone, timedelta

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

datetime(*args, tzinfo=utc_offset(x))
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*som 6

所述datetime模块文档包含一个例子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
Run Code Online (Sandbox Code Playgroud)

从Python 3.2开始,不再需要提供此代码,因为datetime.timezone并且datetime.timezone.utc包含在datetime模块中,应该使用它.