Django with system timezone setting vs user's individual timezones

前端 未结 6 517
無奈伤痛
無奈伤痛 2021-02-02 15:01

How well does Django handle the case of different timezones for each user? Ideally I would like to run the server in the UTC timezone (eg, in settings.py set TIME_ZONE=\"UTC\")

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-02 15:42

    Django doesn't handle it at all, largely because Python doesn't either. Python (Guido?) has so far decided not to support timezones since although a reality of the world are "more political than rational, and there is no standard suitable for every application."

    The best solution for most is to not worry about it initially and rely on what Django provides by default in the settings.py file TIME_ZONE = 'America/Los_Angeles' to help later on.

    Given your situation pytz is the way to go (it's already been mentioned). You can install it with easy_install. I recommend converting times on the server to UTC on the fly when they are asked for by the client, and then converting these UTC times to the user's local timezone on the client (via Javascript in the browser or via the OS with iOS/Android).

    The server code to convert times stored in the database with the America/Los_Angeles timezone to UTC looks like this:

    >>> # Get a datetime from the database somehow and store into "x"
    >>> x = ...
    >>>
    >>> # Create an instance of the Los_Angeles timezone
    >>> la_tz = pytz.timezone(settings.TIME_ZONE)
    >>>
    >>> # Attach timezone information to the datetime from the database
    >>> x_localized = la_tz.localize(x)
    >>>
    >>> # Finally, convert the localized time to UTC
    >>> x_utc = x_localized.astimezone(pytz.utc)
    

    If you send x_utc down to a web page, Javascript can convert it to the user's operating system timezone. If you send x_utc down to an iPhone, iOS can do the same thing, etc. I hope that helps.

提交回复
热议问题