Linkachus 17
Linkachus 17

Reputation: 33

Python datetime does not sync with system time

i'd like to know how to sync datetime with system time in real time. what i mean is the code always prints the same hour same minute and same seconds if i loop the code. this is my code

from datetime import datetime
import os
from time import sleep


def clear():
    os.system('cls')

now = datetime.now()
current_time = now.strftime("%H:%M:%S")

while True:
    time = print("Current Time =", current_time)
    sleep(1)
    clear()

i need help for this thx!

The image

Upvotes: 0

Views: 998

Answers (2)

Linkachus 17
Linkachus 17

Reputation: 33

Thanks for the answer! i also modify the code a little bit to make it a little bit better

from datetime import datetime
from time import sleep


while True:
     now=datetime.now()
     current_time=now.strftime("%H:%M:%S")
     time=print("Current Time : ", current_time, end=\r)
     sleep(1)

Upvotes: 0

exhuma
exhuma

Reputation: 21747

You are currently creating the date-time object only once with the line. This means the time is only looked up once and then that value is stored in the variable.

now = datetime.now()
current_time = now.strftime("%H:%M:%S")

All you need to do is move those two lines into your loop. That way, the time is looked up on each loop iteration and you get new values. The modified code:

from datetime import datetime
import os
from time import sleep


def clear():
    os.system('cls')

while True:
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    time = print("Current Time =", current_time)
    sleep(1)
    clear()

Upvotes: 3

Related Questions