Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get timezone-aware midnight datetime in python? [duplicate]

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)

like image 664
eugene Avatar asked Oct 22 '22 05:10

eugene


1 Answers

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.

like image 52
ddipasquo Avatar answered Oct 24 '22 09:10

ddipasquo