2

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.

2 Answers 2

5

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)
Sign up to request clarification or add additional context in comments.

Comments

2

Another option is

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.