0

I use Django 3 + Bootstrap 4 + MySQL 5.7 on a Laragon server, all on Windows 10.

My setting in Django : TIME_ZONE = 'Europe/Paris'

My setting in MySQL : TIME_ZONE = SYSTEM (My system is configured with 'Europe/Paris')

When I use a timezone.now() in Django, or a CURRENT_TIMESTAMP in MySQL, I have no problem, the right time is displayed. But my data imported from MySQL are displayed wrongly: with a +2 hours error. For what I have read on the subject, the cause can be the absence of data in MySQL time_zone table, on the server. What's your point of view ? Am I on the good track ? I don't want to make a mistake, so I prefer to have a confirmation first.

And do you think it's good to keep the setting so in MySQL. Shouldn't I prefer TIME_ZONE = 'Europe/Paris' instead of TIME_ZONE = SYSTEM ?

Frederic
  • 115
  • 10

2 Answers2

0

The date data kept in database is always in Greenwich Mean Time (GMT) and django changes it based on the "TIME_ZONE" choice. So when you recieve time data directly from database it is displayed as GMT. If you have to convert it you need to use tz.

from dateutil import tz

to_zone = tz.tzlocal()
datefromdatabase.astimezone(to_zone).date()

Bon courage!

mattarello
  • 219
  • 2
  • 11
  • First, I want to tank you for your response. Second, I followed your suggestion, and found another way when my IDE proposed me a `template_local_timezone` auto-completion. After following the track, and reading the documentation, I found a simple and clean option, and I think it's better for me because I'm dealing with objects, not just a datetime. And I want to use the possibility of Django first. So I will give my solution just below. – Frederic Jun 22 '20 at 22:53
0

I found a simple solution whit the Template tags in the Django doc : Time zones

{% load tz %}

{% localtime on %}
    {{ value }}
{% endlocaltime %}

{% localtime off %}
    {{ value }}
{% endlocaltime %}

For me I just had to use {% localtime off %} Simple as that.

Frederic
  • 115
  • 10