Python How to sleep until a specific timestamp "DD-MM-YYYY HH:MM:SS"

Question:

So I have the following timestamp:
23-03-2023 10:11:00

How is it possible in python to sleep from the current time until the timestamp while printing the remaining time in hours-minutes-seconds?

I don’t get quiet the logic of all the different timestamp formats.

I have seen several threads where just a simple time delta gets calculated but my intuition tells me that this is not the right way.

like this:

t1 = datetime.datetime.now()

# other stuff here
t2 = datetime.datetime.now()
delta = t2 - t1
if delta.seconds > WAIT:
    # do stuff
else:
    # sleep for a bit

Maybe you guys have any ideas.

Asked By: realsuspection

||

Answers:

Try subtracting the dates (but check that it’s not negative), then using the .total_seconds() function to get the time difference in seconds:

import time
import datetime


def sleepUntil(t2):
    t1 = datetime.datetime.now()
    if t1 > t2:
        return
    td = t2 - t1
    for i in range(int(td.total_seconds()), 0, -1):
        print(f'{i//3600} hours, {(i//60)%60} minutes, and {i%60} seconds')
        time.sleep(1)


sleepUntil(datetime.datetime(2023, 3, 13, 9, 27, 50))
Answered By: Michael M.

My interpretation is that you’re trying to develop some kind of countdown timer where the "timeout" date/time is expressed as a string. If so, you could try this:

from datetime import datetime
from time import sleep

CSI = 'x1B['

def wait_until(timestamp):
    until = datetime.strptime(timestamp, '%d-%m-%Y %H:%M:%S')
    print(f'{CSI}?25l', end='') # hide cursor
    while (now := datetime.now()) < until:
        dt = datetime.fromtimestamp((until - now).seconds-3600)
        ft = datetime.strftime(dt, '%H:%M:%S')
        print(f'{ft}r', end='')
        sleep(1)
    print(f'{CSI}?25h') # show cursor

wait_until('12-03-2023 15:33:55')
Answered By: DarkKnight
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.