1

In my django application i'm confronting two datetime objects (self.dueDate is a date object):

ref_time = timezone.localtime(timezone.now(), timezone.get_default_timezone() )
threshold = datetime.combine( self.dueDate, 
                               time(tzinfo=timezone.get_default_timezone())) 
           - timedelta(days = 1) 

I'm constructing them to have the same timezone (which they have), but they end up having two different UTC offsets.

>>>print threshold, threshold.tzinfo
2015-03-13 12:08:00+00:50 Europe/Rome 
>>>print ref_time, ref_time.tzinfo
2015-03-13 12:48:29.372984+01:00 Europe/Rome

Why is this happening? How can it be that there are two different offsets for the same tz? (and why would that offest be 50 minutes?)

pnjun
  • 15
  • 2
  • unrelated: make sure you know the difference between [default time zone and current time zone](https://docs.djangoproject.com/en/1.8/topics/i18n/timezones/#default-current-time-zone) – jfs Mar 13 '15 at 20:39

1 Answers1

1

A timezone may have different utc offsets at different times. time(tzinfo=tz) uses a default utc offset e.g., for the earliest date that is most likely is not what you want. See:

To get the current time in tz timezone as an aware datetime object:

from datetime import datetime

ref_time = datetime.now(tz)

To get a midnight a day before self.dueDate as an aware datetime object:

from datetime import time as datetime_time, timedelta
from django.utils import timezone

midnight_yesterday = datetime.combine(self.dueDate, datetime_time()) - timedelta(1)
threshold = timezone.make_aware(midnight_yesterday)

Note: threshold may be more/less than 24 hours ago, see How can I subtract a day from a python date?.

Community
  • 1
  • 1
jfs
  • 346,887
  • 152
  • 868
  • 1,518
  • Thanks a lot, using timezone.make_aware() instead of setting the tzinfo did it. You saved my day! – pnjun Mar 14 '15 at 15:04
  • 1
    @pnjun: be careful if you perform datetime arithmetics that may cross DST boundary. `make_aware()` along won't fix it e.g., if you want exactly 24 hours ago then you need a different code. See the last link in the answer. – jfs Mar 14 '15 at 15:10