Seconds until end of day in python
Asked Answered
V

6

7

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?

Vilhelmina answered 31/8, 2017 at 16:19 Comment(3)
This question is essentially a dupe of the other question just do 24*60*60 - seconds_since_midnightLeopoldoleor
It's not immediately obvious to a person trying to implement seconds until end of day to search for seconds since midnight. Furthermore, I would argue that your line is not as clean as the solution here. Also according to Jim Lewis in the comments below, not every day has 24*60*60 seconds.Vilhelmina
indeed 1 day each year has 25*60*60 while another has 23*60*60, at least where daylight savings is followedLeopoldoleor
V
18

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.

Vilhelmina answered 31/8, 2017 at 16:19 Comment(3)
Your second solution can fail on days where daylight saving time starts or stops. Not every day has 86,400 seconds.Fashoda
Thanks for the heads up.Vilhelmina
One more - you may replace the value of dt to be assigned immediately with the call of the function. Avoiding additional logic = faster code.Helpmate
A
2
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
Aflcio answered 15/10, 2018 at 9:51 Comment(0)
G
2

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)
Gamine answered 7/6, 2021 at 18:4 Comment(1)
Code-only answers are not particularly helpful. Please add some descriptions of how this code solves the problem.Mayes
S
0

The number of seconds untile the end of a day is the difference between the amounts of total seconds in a day and seconds passed from the start of the day:

import datetime
seconds_in_a_day = 86400  # the number of seconds in one day
dt = datetime.datetime.now()
midnight = datetime.datetime.combine(dt.date(), datetime.time())  # current date with zero time (00:00:00)
seconds_since_midnight = (dt - midnight).seconds  # the number of seconds since the beginning of the day
seconds_until_end_of_day = seconds_in_a_day - seconds_since_midnight  # the number of seconds remaining until the end of the day
Subtitle answered 17/10, 2019 at 10:14 Comment(1)
I think like Jim Lewis said, the days where we have daylight savings start/stop do not have 86400 secondsVilhelmina
B
0

If you need UTC, this one-liner works fine.

remSeconds = 86400 - time.time() % 86400

Britzka answered 13/6 at 16:34 Comment(0)
L
-1

I have recently went through this question and tried the solution but solution didn't work for me as i feel it needs latest solution so i came up with solution by using uni time stap.

def when_to_call():
    current_time = timezone.now()+timedelta(hours=5)
    uni_current_time = current_time.timestamp()

    next_day = current_time  + timedelta(days=1)
    next_day =next_day.strftime("%Y-%m-%d")+" 00:00:00"
    next_day =  datetime.strptime(next_day,"%Y-%m-%d %H:%M:%S")
    uni_next_day = next_day.timestamp()

    total_seconds = uni_next_day- uni_current_time
    print(uni_next_day- uni_current_time-3600)
    return total_seconds
Logic answered 7/12, 2022 at 22:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.