Python 如何设置日期时间的UTC偏移量?
我的基于Python的web服务器需要使用客户端的时区(由UTC偏移量表示)执行一些日期操作。如何使用指定的UTC偏移量作为时区构造datetime对象?包含一个表示固定偏移量的示例Python 如何设置日期时间的UTC偏移量?,python,datetime,timezone,Python,Datetime,Timezone,我的基于Python的web服务器需要使用客户端的时区(由UTC偏移量表示)执行一些日期操作。如何使用指定的UTC偏移量作为时区构造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 # U
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,不再需要提供此代码,因为和包含在datetime
模块中,因此应改为使用。使用:
另一方面,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))
但是,请注意,“此类对象不能用于表示在一年中不同日期使用不同偏移或对民用时间进行历史更改的位置的时区信息。”这通常适用于严格依赖UTC偏移的任何时区转换。内置日期UTIL很好,但有一定的局限性;请看和,以便更方便地处理TZ。我想您不知道实际的区域名称,只知道偏移量?您可以指定偏移量的格式吗?整数小时?某种字符串?回显Mark的点-确保您理解偏移量不是时区。请参阅“感谢”中的“时区!=偏移”。这比我在互联网上找到的为每个时区创建tzinfo子类的疯狂建议有很大帮助,效果也更好。也许值得注意的是,pytz中有一个功能相当的类:@GordStephen您可以随时留下自己的答案。Python的较新版本包括
timezone
类,因此我将更新我的答案,感谢您的发言。
>>> dateutil.parser.parse('2013/09/11 00:17 +0900')
datetime.datetime(2013, 9, 11, 0, 17, tzinfo=tzoffset(None, 32400))
from datetime import datetime, timezone, timedelta
# offset is in seconds
utc_offset = lambda offset: timezone(timedelta(seconds=offset))
datetime(*args, tzinfo=utc_offset(x))