I'm working on a django project and i got confused about the timezones.
I have a campaing object, it has publish_start
and publish_end
dates.
example output from the console;
campaingObject.publish_start
datetime.datetime(2015, 9, 1, 0, 0)
campaingObject.publish_end
datetime.datetime(2015, 9, 28, 10, 10)
I want to get campaing objects that are active now. That means publish start is less then current time, end time is greater then current time.
When i call:
datetime.now()
datetime.datetime(2015, 9, 28, 5, 42, 37, 448415)
This result is not in my timezone. I can get my own time info with
datetime.now(pytz.timezone('Europe/Istanbul'))
but this time i can not compare values to find which objects are active right now.
datetime.now(pytz.timezone('Europe/Istanbul')) > campaingObject.publish_end
TypeError: can't compare offset-naive and offset-aware datetimes
How can i compare this times to find which objects are active right now?
You can use the make_aware
function from django on your naive datetime objects. You will then have to specify the time zone of your naive timestamps.
now_ts = datetime.now(pytz.timezone('Europe/Istanbul'))
now_ts > make_aware(campaingObject.publish_end, pytz.timezone('Europe/Istanbul'))
https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.timezone.make_aware
On the other hand, you could also use the make_naive
function to remove the timezone information from your now() timestamp:
now_ts = datetime.now(pytz.timezone('Europe/Istanbul'))
now_naive = make_naive(now_ts, pytz.timezone('Europe/Istanbul'))
now_naive > campaingObject.publish_end
https://docs.djangoproject.com/en/1.8/ref/utils/#django.utils.timezone.make_naive