There’s another question here that asks how many seconds since midnight – this question is the opposite.
How do I get the seconds until the end of the day, from the current time, using python?
Advertisement
Answer
The cleanest way I found to accomplish this is
JavaScript
x
10
10
1
def time_until_end_of_day(dt=None):
2
# type: (datetime.datetime) -> datetime.timedelta
3
"""
4
Get timedelta until end of day on the datetime passed, or current time.
5
"""
6
if dt is None:
7
dt = datetime.datetime.now()
8
tomorrow = dt + datetime.timedelta(days=1)
9
return datetime.datetime.combine(tomorrow, datetime.time.min) - dt
10
Taken from http://wontonst.blogspot.com/2017/08/time-until-end-of-day-in-python.html
This however, is not the fastest solution – you can run your own calculations to get a speedup
JavaScript
1
5
1
def time_until_end_of_day(dt=None):
2
if df is None:
3
dt = datetime.datetime.now()
4
return ((24 - dt.hour - 1) * 60 * 60) + ((60 - dt.minute - 1) * 60) + (60 - dt.second)
5
timeit results:
Slow: 3.55844402313 Fast: 1.74721097946 (103% speedup)
As pointed out by Jim Lewis, there is a case where this faster function breaks on the day daylight savings starts/stops.