Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have Django DateTimeField without timezone?

I have searched for this, and could not find any notes or tutorials.

like image 703
Sagar Avatar asked Mar 09 '16 06:03

Sagar


People also ask

What is the default timezone setting in Django?

Django's timezone is set to UTC by default. If your timezone is not UTC, you can change it using the procedure below: Open the setting.py file in the directory of our project.

How does Django use timezone now?

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 is Django default datetime format?

DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime.


1 Answers

When you set USE_TZ = True(see USE_TZ for more info) in your settings, Django stores date and time information in UTC in the database otherwise it will store naive date time (date time without timezone).

The default settings.py file created by django-admin startproject includes USE_TZ = True for convenience.

So you have to set USE_TZ = False in your settings to avoid attaching timezone.

NOTE: However you cannot detach timezone only for a particular field. By following my suggestion above, you detach timezone from the entire database, so my guess is that it's better to use a CharField to store date without timezone.

You can try to override the default save handler and remove the timezone from DatetimeField before saving the item into the database, by defining a save method for your model:

def save(self, *args, **kwargs):
    self.datetime_field = self.datetime_field.replace(tzinfo=None)
    super(MyModel, self).save(*args, **kwargs)
like image 165
Andriy Ivaneyko Avatar answered Oct 23 '22 14:10

Andriy Ivaneyko