5

I'm working in django, but standard python solution is ok too.

I'm converting a code which uses a naive-datetime to use aware-datetime.

Below is the original code:

today = datetime.today()
MyClass.objects.filter(datetimefield__range=(today, today+datetime.timedelta(1)) )

How do I convert it to use timezone-aware time?

If the time is jun/3rd/7:20pm locally,
I'd like to get datetime range of [jun/3rd/00:00am, jun/4th/00:00am] (midnight to midnight which will include now)

zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
eugene
  • 39,839
  • 68
  • 255
  • 489
  • 1
    What timezone should midnight be *in*? UTC, the server timezone or the timezone of the visitor to your site? – Martijn Pieters Jul 19 '13 at 09:20
  • I'd suggest using `dateutil` library - http://labix.org/python-dateutil – Jan Spurny Jul 19 '13 at 09:50
  • 1
    @JanSpurny: No, that's a great library for parsing and relative date arithmetic. But [Django supports `pytz`](https://docs.djangoproject.com/en/1.5/topics/i18n/timezones/) out of the box, so why not stick with that? – Martijn Pieters Jul 19 '13 at 10:11

1 Answers1

4

I know this is very old, but using django.utils.timezone this is fairly straightforward. (nothing concerning timezones ever seems easy to me)

# this is could be any datetime.date
my_date = timezone.now().date()
dt_at_local_midnight = timezone.make_aware(
    timezone.datetime.combine(my_date, time.min), 
    timezone.get_current_timezone())

and alternative that might be better is listed in the first comment below.

ddipasquo
  • 545
  • 4
  • 7
  • the first example is incorrect. It may create an unnormalized time (wrong offset) (`.replace()` method may cross a UTC transition boundary). The second example doesn't recognize ambiguous or non-existing times - it silently returns *some* value (it is ok in most cases but you should be aware about it). See [my answer to the duplicate question](http://stackoverflow.com/a/11236372/4279) that raises an exception in such cases as an alternative. – jfs Oct 30 '14 at 09:31
  • That makes sense.. editing the answer, and trying to figure a way to give credit, was looking for the localize method. – ddipasquo Oct 31 '14 at 16:26