Django Datetime Query - python

What's the most efficient way to query for objects created today (or for a specific day a given number of days in the past) in a timezone aware way in Django?
I know there are a lot of questions about this, but most answers don't incorporate timezone awareness, there doesn't seem to be any definitive recent answers, and most solutions will produce the naive datetime warning:
RuntimeWarning: DateTimeField received a naive datetime (2012-10-23
00:00:00) while time zone support is active.
I'm running Django 1.5 with timezone support and am using pytz and the UTC timezone throughout.

Django has a built-in function to convert naive datetime objects to timezone aware ones:
from django.utils import timezone
enlightened_date = timezone.make_aware(naive_date, timezone.utc)

Another option is
from django.utils.timezone import utc
utcnow = datetime.utcnow().replace(tzinfo=utc)

Related

Save timezone aware datetime with its timezone

I'm looking for a way to save datetimes with a specific timezone other than the established timezone, however I have the following settings:
TIME_ZONE = "UTC"
USE_TZ = True
This is convenient, since for the most part I want dates to be saved in UTC, however sometimes I need to keep track of the local datetimes the user setup.
Anyone has any idea how to save a datetime without being converted to the default timezone (UTC)?
I am using PostgreSQL, so I don't know if this is possible...
Any tips are welcome.
Watch out from storing dates with their timezone in database systems, as there are way too many years of questionable implementations piled up everywhere, from the engines themselves, thought the clients, to the various third party libraries (including the Django ORM).
For example, from the Postgres documentation:
All timezone-aware dates and times are stored internally in UTC. They
are converted to local time in the zone specified by the TimeZone
configuration parameter before being displayed to the client.
This means that if you save a datetime localized on timezone "Europe/Rome" from Django, with a client setup to use timezone "America/New_York" and then you read it with a client configured with timezone "Europe/London" you will get the British time corresponding to the original datetime, no matter what.
The only reliable way that I found for dealing with time zones using database systems is to save the timezone separately. For example, in a "timezone" filed of the user profile, or using a combination of a "timestamp" + "timezone" fields if storing events which are somehow sensitive to the timezone (i.e. logins, sensor readings, etc.).
In this way you can store all timestamps in UTC (which is what Postgres will do in any case anyway), and then localize them in your application once they are out from the database, which is much clearer, robust, and database-system independent.
Note that if you want to filer your timestamps (i.e. from, to) you will need to perform the queries on UTC, and if you want use time math (i.e. all logins of user X on mondays on timezone "America/New_York") it is going to be a pain in any scenario (you can get a taste here: PostgreSQL date() with timezone).

Django DateTime

I'm using Django and when I retrieve instance (with objects.all()) the models.DateTime are changing so that 7 hours are added.
I'm in the US Pacific time zone and I'm guessing that my DB is defined as UTC I'm using PostgreSQL and I can't figure out where is the setting for time zone.
One other thing I'm also getting this warning:
RuntimeWarning: DateTimeField received a naive datetime while time zone support is active.
Maybe the two are connected?
settings.py:
TIME_ZONE = 'America/Los_Angeles'
# database not use UTC
USE_TZ = False
see this

DateTimeProperty time-zone

Using GEA and trying to set the time-zone for the DateTimeProperty below. I would like to set the timezone in the model class and not when creating the entry.
class Person(ndb.Model):
date_created = ndb.DateTimeProperty(auto_now_add=True)
You are not setting the timezone, you are setting the datetime, when you create the entity.
The timezone you would like should stored seperately. All appengine datetime functionality works as UTC.
YOu should convert to UTC when performing queries, and to the timezone you want when displaying content.
The datastore does not store timezones (see the documentation): all datetimes are naive. You need to be sure to always convert times to and from UTC when saving and loading data.

Using both naive and timezone aware datetimes in Django

The Django docs are pretty clear that naive datetimes should not be used, but I have a use case that I imagine is fairly common where I think I need them. Sometimes it is necessary in my project to query for objects across timezones, but based on local times.
For example, and this is just a contrived example, let's say I want to find all users who last updated their profile between 4 and 5 PM on a given day, according each user's local timezone. I could simply do this as:
qs = User.objects.filter(profile__datelastupdated__gte=datetime(2013,4,1,16))
qs = qs.filter(profile__datelastupdated__lte=datetime(2013,4,1,17))
However, because I have timezone support active this causes the warning:
RuntimeWarning: DateTimeField received a naive datetime (YYYY-MM-DD HH:MM:SS) while time zone support is active.
I understand why the warning is getting thrown, so my question is: am I not thinking about datetimes the right way? Is there an idomatic Django way to have the specificity of tz aware datetimes when that's what you want, and also have the desired genericness that is sometimes needed that is provided by naive datetimes?
You have to filter for database with datetime + timezone all of dates in database are stored as utc always. If you provide date without time zone django treat it default like utc and gives you warring.
If you support timezones you have to store user timezone.
Ask database with date + current user time zone the same with putting date.

Do I need timezone support in Django?

I am developing a Django application that is based around event information. My client is sending all date/time information in UTC and making the conversion to local time. These are then sent to the server as a string. Furthermore, I'm using Postgres as the DB which also stores information in UTC.
Timezone support is active, but I am placing naive datetimes into Django and am receiving warnings. Do I even need time zone support for my application?
If so, how can I resolve the warnings?
USE_TZ = True # to activate time zone setting.
TIME_ZONE = 'America/Chicago' # set your timezone
When you activate time zone setting, DJango shows warning for each time you set Naive date time in your cod. Nothing to panic. You need to change your code to use Aware date time step by step.
https://docs.djangoproject.com/en/dev/topics/i18n/timezones/#concepts
from django.utils.timezone import utc, now
class SomeModel(Model):
schedule = django_models.DateTimeField(default=now)
I would highly encourage that you use pytz module. It makes working with timezones less painful.

Categories

Resources