How to set UTC offset for datetime?

后端 未结 3 1590
遇见更好的自我
遇见更好的自我 2021-02-07 05:08

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 spe

3条回答
  •  不要未来只要你来
    2021-02-07 05:45

    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.

提交回复
热议问题