SYSTEM NOTICE

Auto translation by AI. Be sure, accuracy, nuances and authorial intent may not be fully reflected.
見出し画像

Django Timezone Handling

[Introduction]

Django's timezone handling is usually something you don't need to worry about, but this is a discussion on why you need to be careful when passing values extracted from datetime objects between the UI and your code.

[Details]

If you set USE_TZ = True, Django's datetime values will be aware (UTC), and appropriate conversions will be applied automatically.

Normally, by using this value (UTC) for calculations or saving it to the database, you can perform processing that is independent of timezones. Within your code, you should basically continue to process them as UTC.

Also, since aware values can be converted based on timezones, Django automatically handles time processing within templates so that the UI uses local time while the retrieved values remain in UTC.

In other words, since Django automatically handles the conversion of datetime values between the UI (local time) and your code (UTC), you don't need to be particularly conscious of it when using them as datetime objects.

However, if you extract the year, month, hour, etc., within your code and use those values in a template, they are just numbers, so naturally, the conversion will not work. Therefore, you need to perform the appropriate conversion.

[Example]

For example, if you pass the following year, month, day, and hour to a template when it is 7:00 AM on January 1, 2018, in Japan Standard Time, they will become year: 2017, month: 12, day: 31, and hour: 22. (Because UTC is 9 hours behind Japan Standard Time).

now = timezone.now()
year = now.year
month = now.month
day = now.day
hour = now.hour

In this case, to pass year: 2018, month: 1, day: 1, and hour: 7 to the template as intended, use timezone.localtime() .

now = timezone.localtime(timezone.now())
year = now.year
month = now.month
day = now.day
hour = now.hour

いいなと思ったら応援しよう!

X3BLANK Note やるからには、サポートがいただけるような役立つ記事を書きたいものです。サポートは資料購入に宛てます。