Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seconds until end of day in python

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?

like image 925
wonton Avatar asked Aug 31 '17 16:08

wonton


3 Answers

The cleanest way I found to accomplish this is

def time_until_end_of_day(dt=None):
    # type: (datetime.datetime) -> datetime.timedelta
    """
    Get timedelta until end of day on the datetime passed, or current time.
    """
    if dt is None:
        dt = datetime.datetime.now()
    tomorrow = dt + datetime.timedelta(days=1)
    return datetime.datetime.combine(tomorrow, datetime.time.min) - dt

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

def time_until_end_of_day(dt=None):
    if df is None:
        dt = datetime.datetime.now()
    return ((24 - dt.hour - 1) * 60 * 60) + ((60 - dt.minute - 1) * 60) + (60 - dt.second)

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.

like image 142
wonton Avatar answered Nov 11 '22 11:11

wonton


from datetime import datetime
from datetime import timedelta

def seconds_until_end_of_today():
    time_delta = datetime.combine(
        datetime.now().date() + timedelta(days=1), datetime.strptime("0000", "%H%M").time()
    ) - datetime.now()
    return time_delta.seconds
like image 33
gaozhidf Avatar answered Nov 11 '22 11:11

gaozhidf


You can use DateTime and timedelta together to figure out how many seconds are left till midnight.

from datetime import timedelta, datetime


def seconds_till_midnight(current_time):
    """
    :param current_time: Datetime.datetime 
    :return time till midnight in seconds: 
    """
    # Add 1 day to the current datetime, which will give us some time tomorrow
    # Now set all the time values of tomorrow's datetime value to zero, 
    # which gives us midnight tonight
    midnight = (current_time + timedelta(days=1)).replace(hour=0, minute=0, microsecond=0, second=0)
    # Subtracting 2 datetime values returns a timedelta
    # now we can return the total amount of seconds till midnight
    return (midnight - current_time).seconds


if __name__ == '__main':
    now = datetime.now()
    seconds_left_in_the_day = seconds_till_midnight(now)
    print(seconds_left_in_the_day)
like image 24
Fry Avatar answered Nov 11 '22 11:11

Fry