简体   繁体   中英

Django Datetime Query

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM