0

Have a program to get a date count down. I don't want to print the milliseconds, please help here is my program in python:

import time
import datetime
while (datetime.datetime.now() != datetime.datetime (2018,5,5,19,30)):
    print (datetime.datetime (2018,5,5,19,30) - datetime.datetime.now())
    time.sleep(1.0)

This is my current output: 54 days, 3:54:53.603289

Would like: 54 days, 3:54:53, but don't know how to do it.

2 Answers 2

3

You are looking for datetime.replace(microsecond=0), which will:

Return a datetime with the same attributes, except for those attributes given new values by whichever keyword arguments are specified.

import time
import datetime
while (datetime.datetime.now() != datetime.datetime (2018,5,5,19,30)):
    print (datetime.datetime (2018,5,5,19,30) - datetime.datetime.now().replace(microsecond=0))
    time.sleep(1.0)

Output:

54 days, 3:49:31
54 days, 3:49:30
54 days, 3:49:29
54 days, 3:49:28
54 days, 3:49:27
54 days, 3:49:26
54 days, 3:49:25
54 days, 3:49:24
54 days, 3:49:23
Sign up to request clarification or add additional context in comments.

Comments

0

As you have found, there are no good formatting options for a timedelta object. I would recommend you pre-calculate an end_time and also use < rather than waiting for the times to match. In the event your PC is busy at the exact second, your loop might miss the match. By using < it will also catch it:

from datetime import datetime
import time

end_time = datetime(2018, 5, 5, 19, 30)

while datetime.now() < end_time:
    print(end_time - datetime.now().replace(microsecond=0))
    time.sleep(1.0)      

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.