Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - get midnight tomorrow night in timezone format

Tags:

django

Im trying to get a list of all events occuring tomorrow from a django queryset. i assumed i needed tomorrow at midnight until tomorrow at 11:59pm. i think my tomorrow_end variable will be correct if tomorrow_start was set to 00:00:00 currently it gets the exact time now.

Can someone please tell me how to alter the time on the below to 00:00:00?

tomorrow_start = timezone.now() + timedelta(1)
tomorrow_end = tomorrow_start + timedelta(hours=11,minutes=59)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=tomorrow_start, end_time__lte=tomorrow_end)
like image 360
AlexW Avatar asked Jun 14 '26 00:06

AlexW


2 Answers

Probably it doesn't look very elegant but you could use datetime.combine to obtain tomorrow midnight:

from datetime import datetime, timedelta, time 
tomorrow_start = datetime.combine(timezone.now().date(), time(0, 0)) + timedelta(1)
like image 131
neverwalkaloner Avatar answered Jun 16 '26 12:06

neverwalkaloner


You can also do this:

import pytz
from datetime import datetime, timedelta
timezone = pytz.timezone('Europe/London')
dt_now = datetime.now(timezone)
tomorrow_start = datetime(dt_now.year, dt_now.month, dt_now.day, tzinfo=timezone) + timedelta(1)
tomorrow_end = tomorrow_start + timedelta(hours=12)
maintenance = CircuitMaintenance.objects.filter(start_time__gte=tomorrow_start, end_time__lt=tomorrow_end)

Note that we changed the query to get everything less than 12 hours from the start time. This way you capture the 60 seconds from 11:59:00 to 12:00:00.


Sample output from ipython:

In [1]: import pytz
   ...: from datetime import datetime, timedelta
   ...: timezone = pytz.timezone('Europe/London')
   ...: dt_now = datetime.now(timezone)
   ...: tomorrow_start = datetime(dt_now.year, dt_now.month, dt_now.day, tzinfo=timezone) + timedelta(1)
   ...: tomorrow_end = tomorrow_start + timedelta(hours=12)
   ...:

In [2]: print timezone
Europe/London

In [3]: print dt_now
2017-01-17 19:42:23.044706+00:00

In [4]: print tomorrow_start
2017-01-18 00:00:00-00:01

In [5]: print tomorrow_end
2017-01-18 12:00:00-00:01
like image 35
2ps Avatar answered Jun 16 '26 12:06

2ps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!