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)

3
  • 1
    What timezone should midnight be in? UTC, the server timezone or the timezone of the visitor to your site? Commented Jul 19, 2013 at 9:20
  • I'd suggest using dateutil library - labix.org/python-dateutil Commented Jul 19, 2013 at 9:50
  • 1
    @JanSpurny: No, that's a great library for parsing and relative date arithmetic. But Django supports pytz out of the box, so why not stick with that? Commented Jul 19, 2013 at 10:11

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 that raises an exception in such cases as an alternative.
That makes sense.. editing the answer, and trying to figure a way to give credit, was looking for the localize method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.