How to set UTC offset for datetime?

2019-03-18 11:03发布

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?

3条回答
Luminary・发光体
2楼-- · 2019-03-18 11:18

The datetime module documentation contains an example tzinfo class that represents a fixed offset.

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.timezone and datetime.timezone.utc are included in the datetime module and should be used instead.

查看更多
Viruses.
3楼-- · 2019-03-18 11:24

Using 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))
查看更多
一纸荒年 Trace。
4楼-- · 2019-03-18 11:24

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

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.

查看更多
登录 后发表回答