Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How django time zone works with model.field's auto_now_add

I suppose time zone management was added to Django 1.4, so the problem is quite new.

I used a simple model

class Sample(models.Model):     ...     date_generated = models.DateTimeField(auto_now_add = True) 

When I try to retrieve a newly created record its fails.

min_datetime = datetime.now() - timedelta(seconds = 300) sample = Sample.objects.get(date_generated__gte = min_datetime) 

and the server issues a warning.

DateTimeField received a naive DateTime (2012-06-29 15:02:15.074000) while time zone support is active. 

I figured out two solutions to that problem.

  1. Disable time zone management in settings.py

     USE_TZ = False  

but this is not always desirable. 2. changing

    date_generated = models.DateTimeField(auto_now_add = True)  

to

    date_generated = models.DateTimeField(default=datetime.now())  

is the solution that keeps time zone management working

like image 949
user1491229 Avatar asked Jun 29 '12 13:06

user1491229


People also ask

How does Django time zone work?

Overview. When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user's time zone in templates and forms.

What is Auto_now_add in Django?

auto_now_add. Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it's not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored.

What is the difference between Auto_now and Auto_now_add?

auto_now - updates the value of field to current time and date every time the Model. save() is called. auto_now_add - updates the value with the time and date of creation of record.


1 Answers

Use timezone utils of django

from django.utils import timezone date_generated = models.DateTimeField(default=timezone.now) 
like image 68
ayarshabeer Avatar answered Sep 24 '22 08:09

ayarshabeer