---
slug: "django-でdatetime-で-mysql-検索する時にタイムゾーンがずれてうまく検索できないミス"
title: "Mistakes When Searching MySQL with datetime in Django Due to Time Zone Mismatch"
description: "Since I often make mistakes, here's a note."
url: "https://www.ytyng.com/en/blog/django-でdatetime-で-mysql-検索する時にタイムゾーンがずれてうまく検索できないミス"
publish_date: "2017-01-26T04:11:07Z"
created: "2017-01-26T04:11:07Z"
updated: "2026-02-27T04:27:29.345Z"
categories: ["Django"]
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/2d6565c871004ba88947c18f9ed10950.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

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

<p>Since I often make mistakes, here's a note.</p>
<p>settings</p>
<pre>TIME_ZONE = 'Asia/Tokyo'<br>USE_TZ = True</pre>
<p></p>
<pre>from django.utils import timezone<br><br>now = timezone.now()</pre>
<p></p>
<p>This `now`, when you `repr` it, looks like this:</p>
<pre>datetime.datetime(2017, 1, 26, 4, 4, 56, 53007, tzinfo=&lt;UTC&gt;)</pre>
<p>It's a UTC datetime.</p>
<p>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.</p>
<p>If you extract the date using</p>
<pre>now.date()</pre>
<p>and compare it to a date field stored in MySQL (stored in JST), it will be off by 9 hours, leading to discrepancies.</p>
<p>So, if you need to use the date or want to use `strftime` within Python code,</p>
<pre>from django.utils import timezone<br><br>now = timezone.localtime(timezone.now())</pre>
<p>By converting to localtime,</p>
<pre>datetime.datetime(2017, 1, 26, 13, 4, 56, 53007, tzinfo=&lt;DstTzInfo 'Asia/Tokyo' JST+9:00:00 STD&gt;)</pre>
<p>you will get a datetime with the JST timezone, making it more convenient to use.</p>
<p></p>
