Mistakes When Searching MySQL with datetime in Django Due to Time Zone Mismatch

Django
2017-01-26 13:11 (8 years ago) ytyng

Since I often make mistakes, here's a note.

settings

TIME_ZONE = 'Asia/Tokyo'
USE_TZ = True

from django.utils import timezone

now = timezone.now()

This `now`, when you `repr` it, looks like this:

datetime.datetime(2017, 1, 26, 4, 4, 56, 53007, tzinfo=<UTC>)

It's a UTC datetime.

When displayed in a template, it gets converted to local time, so it appears to be JST. However, it's only converted at the moment you view it; the timezone is still UTC.

If you extract the date using

now.date()

and compare it to a date field stored in MySQL (stored in JST), it will be off by 9 hours, leading to discrepancies.

So, if you need to use the date or want to use `strftime` within Python code,

from django.utils import timezone

now = timezone.localtime(timezone.now())

By converting to localtime,

datetime.datetime(2017, 1, 26, 13, 4, 56, 53007, tzinfo=<DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD>)

you will get a datetime with the JST timezone, making it more convenient to use.

Current rating: 4.8
The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011