AlexW
AlexW

Reputation: 2587

Python - get midnight tomorrow night in timezone format

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)

Upvotes: 3

Views: 3874

Answers (2)

2ps
2ps

Reputation: 15936

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

Upvotes: 2

neverwalkaloner
neverwalkaloner

Reputation: 47364

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)

Upvotes: 5

Related Questions