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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18722196/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:36:18  来源:igfitidea点击:

How to set UTC offset for datetime?

pythondatetimetimezone

提问by lairtech

My Python-based web server needs to perform some date manipulation using the client's timezone, represented by its UTC offset. How do I construct a datetime object with the specified UTC offset as timezone?

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

采纳答案by falsetru

Using dateutil:

使用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))

回答by Mark Ransom

The datetimemodule documentationcontains an example tzinfoclass that represents a fixed offset.

所述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

Since Python 3.2 it is no longer necessary to provide this code, as datetime.timezoneand datetime.timezone.utcare included in the datetimemodule and should be used instead.

由于 Python 3.2 不再需要提供此代码,因为datetime.timezonedatetime.timezone.utc包含在datetime模块中,应改为使用。

回答by falsetru

As an aside, Python 3 (since v3.2) now has a timezone classthat does this:

顺便说一句,Python 3(自 v3.2 起)现在有一个timezone 类可以执行以下操作:

from datetime import datetime, timezone, timedelta

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

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

However, note that "objects of this class cannot be used to represent timezone information in the locations where different offsets are used in different days of the year or where historical changes have been made to civil time." This is generally true of any time zone conversion relying strictly on UTC offset.

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