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.
Comments