Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django.utils.timezone.now returns UTC in default TimeField

I try to prepopulate a TimeField in django_admin with the following code :

from django.utils import timezone

time_start = models.TimeField('Heure de debut',max_length=20, default=timezone.now)

I've installed pytz and also correctly set

TIME_ZONE = 'Europe/Brussels'
USE_TZ = True

and the "now" button in admin correctly sets the time if I click on it. However, it initialy shows the time in UTC (two hours before the actual time in my case)

Am I missing something and is there a way to solve this ? I don't want to use auto_now_add=False because I want to be able to change this time later...

like image 491
Lapin-Blanc Avatar asked Oct 10 '16 07:10

Lapin-Blanc


People also ask

How do I change the default timezone in Django?

The solution to this problem is to use UTC in the code and use local time only when interacting with end users. Time zone support is disabled by default. To enable it, set USE_TZ = True in your settings file. In Django 5.0, time zone support will be enabled by default.

What are the time zone utilities used in Django?

utils. tzinfo , is a support system within Django that stores data and time information in UTC in the database. It uses the time-zone-aware- datetime objects internally and translates them to the user's time zone in templates.

What is Use_tz in Django?

When USE_TZ is False, this is the time zone in which Django will store all datetimes. When USE_TZ is True, this is the default time zone that Django will use to display datetimes in templates and to interpret datetimes entered in forms. ... When django rest framework takes the naive datetime data from request.


1 Answers

To get Time in local timezone as set in settings.py use:

from django.utils import timezone
timezone.localtime(timezone.now())

As for use in django models see this answer here https://stackoverflow.com/a/12654998/1340421

like image 134
IJR Avatar answered Nov 03 '22 07:11

IJR