Django: time zone issue

后端 未结 4 1646
一整个雨季
一整个雨季 2021-02-01 09:44

NOTE: I deleted the question as it existed previously and providing only the relevant info here.

Our database server (RH) has TIME_ZONE = \"Europe/London\" specified. An

4条回答
  •  悲&欢浪女
    2021-02-01 10:31

    Relying on date/time 'automagic' is dangerous and these auto_add model parameters are a trap. Always understand the timezone(s) you are dealing with. Python makes this easier by attaching a tzinfo member to its datetime objects. While these objects are 'naive' by default, I encourage you to always attach tzinfo detail. Still Python needs some extra help with either python-dateutil or pytz (what I use). Here's a universal rule though - always store your datetimes in a database as UTC.

    Why? Your users may be in different locals, mobile phones and laptops travel, servers are misconfigured or mirrored in different timezones. So many headaches. Datetimes should never be naive and if they are (as in a database) and you need the context, also include a timezone field in the table.

    So in your case.

    1. Don't use the auto_now fields, use a custom save() instead.
    2. Store UTC in the database
    3. If you need to know the timezone - for say a user event - store the timezone in the database as well.
    4. Convert to the necessary/requested timezone

    If you are using pytz, the localize() method is great. Python's datetime object has the useful replace() and astimezone().

    One more note, if your database is timezone naive (like MySQL) make sure your datetimes are in UTC and then use replace(tzinfo=None) because the database connector can't handle tz-aware objects.

    Here is a thread with detail on Django's auto_now fields.

提交回复
热议问题