Assuming I've written a Python code, which displays the time as long as you keep the program running on the console. Maybe I'll run my code at 4 AM the first time, and next time at 6 PM and so on. So How could I tell my code to start the clock from 5 AM if I'm running it at 5 AM, for example? To me it seems like my code needs to be connected to some external clock. Can someone help me with this? I really didn't know how to search this question on Google. Any hints, tips or solutions will be greatly appreciated! Thanks in advance :)
Asked
Active
Viewed 136 times
-2
-
What are you trying to achive exactly? One clock that wait until the specified time is reached? – Carlo Zanocco Aug 31 '20 at 07:33
-
Is it possible to have the python code? – Aug 31 '20 at 07:36
3 Answers
1
You can use the "datetime" module.
The syntax would be the following:
from datetime import datetime
now = datetime.now()

MananGandhi1810
- 131
- 10
1
You are looking for a simple custom timer:
import time
def Timer_Tick(delay): #delay = time to wait in seconds
while True:
time_remaining = delay-time.time()%delay # calculate the remaining before execute
time.sleep(time_remaining) # wait the remaining time
# Your code
Timer_Tick(300) # This timer execute each 5 minutes (eg. 14:00, 14:05, 14:10, ..)
You can run this code in a separate thread, so it count for you the time and when executed you run your actions.

Carlo Zanocco
- 1,967
- 4
- 18
- 31
0
If I understand you correctly you want your code to calculate how long it has been since you started its execution. When your program starts call:
from datetime import datetime
start_time = datetime.now()
Then every time you want to check how long it has been since your code started, call:
datetime.now()-start_time
Which outputs
datetime.timedelta(seconds=5, microseconds=358359)

Jeff
- 610
- 4
- 12
-
No, I want my program to display what time it is by the time I run it, and keep track of time until I end the program. But I'm not sure how my program should actually know what time it is every time I run it. – Liana Aug 31 '20 at 07:59
-
1Then simply calling datetime.now() will show you what time it is at execution – Jeff Aug 31 '20 at 08:02