I am writing a site to be served internationally across multiple timezones.

In the settings.py:

TIME_ZONE = 'UTC'
USE_TZ = True

I am wondering if someone from NZ puts in a datetime via models.DateTimeField, does it automatically picks up the current timezone and convert to UTC without any extra code?

I am a bit confused on this paragraph:

The current time zone is the equivalent of the current locale for translations. However, there’s no equivalent of the Accept-Language HTTP header that Django could use to determine the user’s time zone automatically. Instead, Django provides time zone selection functions. Use them to build the time zone selection logic that makes sense for you.

So do I have to override the save method to add the get_current_timezone()?

有帮助吗?

解决方案

The key sentence there is: "However, there’s no equivalent of the Accept-Language HTTP header that Django could use to determine the user’s time zone automatically."

So there's no way for Django to reliably figure out your NZ user's time zone. It's not going to give you the user's time zone - you have to tell it! Specifically, until you explicitly activate() a time zone, the current time zone is just UTC as you defined in your TIME_ZONE setting.

When it comes to user input, the documentation says: "Django interprets datetimes entered in forms in the current time zone and returns aware datetime objects." So, if you've activated the appropriate NZ time zone then the conversion will happen as you expect. But if not, the datetime will be interpreted as being in your default UTC timezone.

How do you figure out the user's timezone? The documentation gives an example of how you can set it based on a value explicitly chosen by the user. I'm sure there are also services out there that try to guess the time zone based on the IP address. Either way, though, Django won't do it for you.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top