Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading