How to set UTC offset for datetime?

后端 未结 3 1546
遇见更好的自我
遇见更好的自我 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:54

    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.

提交回复
热议问题