The timezone for my users is fixed to PST.
I can't make timezone.now() output the correct time. In settings.py I have the timezone set to US/Pacific and USE_TZ=False. Am I doing something wrong? The timezone.now() is 9 hours ahead.
Also, if I want to adjust the timezones some time later, is there a nice way to do it? Django's documentation seems kinda messy in this regard.
USE_TZ = False tells django to ignore timezone information. Switch it to USE_TZ = True and you should be fine.
With this in place, changing timezones in future should be as simple as updating the timezone setting as the timezone is saved with the date when USE_TZ = True
You should really have USE_TZ=True and the timezone set to US/Pacific. Then all the dates will be stored as UTC and converted to PDT on the front-end. This makes it easier if/when you have to change timezones later since all of the datetimes are stored as UTC rather than a naive PDT.
Related
I have a column in my table called "signed_up_date", which I am using the auto_now_add=True parameter with the DateTimeField() function.
I want this function to save timestamps to the PostgreSQL DB in UTC instead of my local time (EST) which it is currently doing.
Barebones version of the model for quick ref below:
class TutorTest(models.Model):
signed_up_on = models.DateTimeField(auto_now_add=True)
Settings.py
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
I thought based on the docs, if I have Time_Zone set to UTC and UTC_TZ set to True, then the default behavior of Django would be to save as UTC.
I know when I check postgresql timezone I get:
SHOW TIMEZONE;
TimeZone
------------
US/Eastern
(1 row)
I just tried a new model with timezone.now() and it looks like in the db shell I get:
datetime.datetime(2022, 9, 21, 14, 36, 16, 670726, tzinfo=datetime.timezone.utc)
But the db saved it as:
2022-09-21 10:35:26.633116-04
I guess it's the DB in this situation? Confused lol
*** EDIT ***
I think I figured it out. The database takes a UTC time and converts to EST, but when I pull the time out django reads it as UTC. Which works for me lol.
The timestamp which is actually saved in the database would be in UTC, but if you are using some sort of tool such as DBeaver (for example) to look into and query the datbase, then that tool would convert the timestamps as per what is put in its configuration and show those converted timestamps to you. But the underlying data in the database is still in UTC.
Hope this helps.
I'm a bit confused by the daylight savings handling. I have working on web notifier application in Django 2.0.6 framework and python 3.6. this application provide scheduling notification. for example users schedule message for some hours later or a few days later. this website is available in only one time zone.
I have use this settings in Django:
...
TIME_ZONE = 'Europe/London'
USE_I18N = True
USE_L10N = True
USE_TZ = True
...
when I run this code in python manage.py shell:
>>> from django.utils import timezone
>>> from datetime import datetime
>>> timezone.now()
>>> datetime.now()
django timezone.now() return to me datetime with tzinfo UTC and datetime.now() return to me correct time information with correct time zone info. when I made USE_TZ=False in django setting to find out timezone.now() in django return correct time zone information like datetime.now(). in Django time zone document said: ''This is handy if your users live in more than one time zone and you want to display datetime information according to each user’s wall clock.good practice to store data in UTC in your database. The main reason is Daylight Saving Time (DST). Many countries have a system of DST, where clocks are moved forward in spring and backward in autumn. If you’re working in local time, you’re likely to encounter errors twice a year, when the transitions happen''
Depending on my project type I'm looking for that what is the best practice for time zone config in my Django settings project and solve that problem Django talk about that in time documentation. Please help me
Thanks.
You should enable USE_TZ. If you look carefully, you'll see that datetime.now() does not specify the timezone (naive time), whereas timezone.now() does (timezone-aware time). With USE_TZ=True, all datetime objects are transformed to the absolute UTC time and timezone aware, so that there's no ambiguity about the actual moment in time.
timezone.now() should give you 14:28 with tzinfo=UTC when in London it's 15:28 (now, in April):
>>> timezone.now()
datetime.datetime(2020, 4, 6, 14, 41, 13, 296983, tzinfo=<UTC>)
>>> datetime.now()
datetime.datetime(2020, 4, 6, 15, 42, 3, 320929) # no tzinfo
Imagine your user sets an alarm for October 25th, 2020, 2:30am. Now this is ambiguous, since this time will occur twice in London: Once during DST and an hour later after we've gone back to winter time and moved our clocks from 3am to 2am. But if you change this to UTC, this won't be ambiguous, there's only one 2020/10/25 2:30 UTC (when Europe/London is in winter time when GMT = UTC). So it either has to be 1:30 or 2:30 (UTC).
So definitely if you're making an app where there's scheduling, use USE_TZ otherwise you'll have issues around DST.
I have deleted all timezone-naive entries out of my Sqlite-DB. So now they remaining entries have a datefield like this:
2016-09-04 13:28:16+00
When I now run my query like this:
result = Feedentry.objects.filter(date_published__gt=timezone('Europe/Berlin').localize(datetime(2016, 8, 31, 17)))
First I receive no error, but as soon as I want to access the result (or len(result)) I receive the following error:
raise ValueError('Not naive datetime (tzinfo is already set)')
Any ideas how to solve it or what I did wrong?
Django always stores datetimes in UTC. And in SQLite it doesn't store any timezone information at all:
[Databases other than PostgreSQL] store datetimes without time zone information. If you switch from USE_TZ = False to USE_TZ = True, you must convert your data from local time to UTC – which isn’t deterministic if your local time has DST.
So first you need to go through your database and convert all the values to UTC; otherwise, Django will not interpret the values correctly.
As for your comparison, it is correct if you're using pytz.timezone and a naive datetime. But the error message implies that whatever datetime you're passing to localize() is already timezone-aware. To convert a timezone-aware datetime you need to use datetime.astimezone(), as noted in the pytz documentation.
I have :
TIME_ZONE = 'Europe/Paris'
USE_L10N = True
USE_TZ = True
in my settings.py file. I am living in Istanbul/Turkey and there is one hour difference between Paris and Istanbul.
In the admin side when selecting a date, django correctly shows 1 hour difference. And using template tag i am getting the datetime i have set in the admin.
But when i pass the datetime via python using beginning_date.strftime("%H:%M") python substracts 1 hour from the value that was set via admin which is not true.
How can i solve this?
Use the Django template defaultfilters to format your dates in Python code.
from django.template.defaultfilters import date as _date
_date(datetime_object, "%H:%M")
And, maybe related: Django cannot reliably use alternate time zones in a Windows. See documentation.
I don't think Turkey has anything to do with it.
My guess is that the one-hour difference you're seeing is between the Paris timezone—which is being used, by default, to interpret and display dates—and UTC—which is being used to store the datetime, and which is the timezone of the datetime returned from the database.
If that's correct, then you can just use django.utils.timezone.localtime to convert the datetime to the current time zone (which by default will be TIME_ZONE):
localtime(beginning_date).strftime("%H:%M")
using django 1.4 I have a model with a datetimefield. I imported django.utils.timezone to use as the default value.
from django.utils import timezone
date = models.DateTimeField(default=timezone.now)
however I still receive the warning about DateTimeField received naive date.
i have set USE_TZ to true so it should be returning aware datetimes
djangos putting in a default date value that isn't tz aware because the field isnt nullable by default. setting null to true means it will just set the date to to NULL instead so the warning isnt raised:
date = models.DateTimeField(default=timezone.now, null=True)
In my case, I kept receiving the issue when I ran tests. This is because of a past migration that incorrectly used datetime instead of timezone. I reverted back to the migration before the one causing the warning, deleted it, ran makemigrations again. This solved the issue for me.
now()
Returns an aware or naive datetime that represents the current
point in time when USE_TZ is True or False respectively.
https://docs.djangoproject.com/en/dev/ref/utils/#django.utils.timezone.now
I know this is side-stepping the issue but have you tried auto_now_add=True on your field instead? No need to use default for what you want.
On the other hand your version should work as well if you have indeed USE_TZ=True.
I'd say it does work, and you get the RunTimeWarning from somewhere where you set the date field directly instead and not from the default. Try to narrow down when is the warning triggered more exactly.