Python datetime does not sync with system time - python

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!

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()

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)

Related

Print time that updates automatically

I want to print the current time on screen in hours and minutes that updates automatically without making a new line, as well as print another line with the seconds that also updates automatically on a second line. Thanks in advance! This is what I have so far:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print("\r" + "Clock: ", current_time, end= ' ')
print("\r" + "\n" + "Seconds: ", current_second, end=' ')
time.sleep(1)
This is what the output looks like: Output
The seconds out like they should, but the time does not
Combining #Rhuamer's answer with your code, you can do something like:
import subprocess
import sys
import time
from datetime import datetime
clear = "cls" if sys.platform == "win32" else "clear"
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\rClock: {current_time}", flush=True, end="\n")
print(f"Seconds: {current_second}", flush=True, end="")
time.sleep(1)
subprocess.run(clear, shell=True)
Try clearing the console with a clear method. Define it like this:
from os import system, name
if name == "nt":
clear = lambda: system("cls")
else:
clear = lambda: system("clear")
and then just call it every loop
The heart of this question is based around how to clear the console and there are a number of good answers here Clear terminal in Python and I recommend you explore it. The other part of the question deals with writing on multiple lines and so I feel this is not quite a duplicate.
I think the easiest way to get what you seek might be to use an f-string and simply do:
import time
from datetime import datetime
while True:
now = datetime.now()
current_time = now.strftime("%I:%M %p")
current_second = now.strftime("%S")
print(f"\033cClock: {current_time}\nSeconds: {current_second}")
time.sleep(1)
If that does not quite work correctly, there are other more slightly extended escape codes you can explore such as \033c\033[3J. I have tested the \033c on a few terminals with success though.
If after reviewing that other question, you feel this is a duplicate, just let me know and I will remove this answer and you can close the question.

Python sleep function not working as expected

I'm sure I am missing something very basic... I have a python script that calls a sleep function. I'd like the main thread (in this case) to sleep for 1 hour (3600 seconds).
Here is the relevant code reproduced:
import time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)
time.sleep(3600)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)
The output after 2 hours is:
Current Time = 08:45:45
Sleep
But my code never exits the sleep function to print the finish time or "Done sleeping" message.
(I added the flush parameter to the print statement to eliminate potential buffering, but I don't think that's relevant here).
Any thoughts on why my code doesn't exit the sleep function after 1 hour?
Thanks.
You could try a loop like this to tell you how long it takes to time out.
import time
from time import perf_counter
from datetime import datetime
start = perf_counter()
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)
# time.sleep(3600)
for i in range(3600):
print("Seconds sleeping:{}".format(i))
time_elapsed = perf_counter() - start
print("Elapsed Time =", time_elapsed)
time.sleep(1)
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)
I added the perf_counter that #Jortega suggested.
I ran it for 1 hour (3600) seconds, and in this case it finished, but also showed the sleep function "drifted" by about 18 seconds over the 1 hour period. Output below:
Seconds sleeping:3597
Elapsed Time = 3615.837408959
Seconds sleeping:3598
Elapsed Time = 3616.842702875
Seconds sleeping:3599
Elapsed Time = 3617.847937667
Current Time = 15:20:32
Done sleeping
This is interesting but unfortunately, I'm still not sure why the following code does not work:
import time
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)
time.sleep(3600)
now = datetime.now() <================== Code never executes.
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)
If anyone has any suggestions, it would be appreciated.

Trying to write a alarm clock in python

I'm trying to write a program to remind a user to take breaks. Here is the code:
import datetime
import os
from playsound import playsound
import time
# current_time = datetime.datetime.now()
# print(current_time)
running = True
while running:
current_time = datetime.datetime.now()
new_time = datetime.datetime.now()
# print(current_time)
breaktime = datetime.timedelta(
days=0,
hours=0,
minutes=1
)
times = datetime.timedelta(seconds=5)
time.sleep(6)
new = current_time + times
if new_time == new:
print("hello")
playsound('Take_Flight.mp3')
running = False
break
The program does not play the sound Take_Flight.mp3 and it does not print hello.
How can I make it work?
I think the reason your alarm does not ring is because of the break statement at the bottom line of your code. The while loop simply ends without looping over and over again as you intended. I believe if you remove that your code will work. As an alternative to what you wrote you can also make the program wait for 5 min and then ring without getting the current time:
while True
time.sleep(300000)
print("hello")
playsound('Take_Flight.mp3')

Execute specific tasks for each specific time and wait for its time (Python)

I would like to create a different task for every specific time and it will wait for the time and continue it day over day.
Below are my code but it only for one task.
import time, datetime
time_now = time.localtime(time.time())
now = []
now = time.strftime("%H:%M:%S", time_now)
value = []
value = time.strftime("15:00:00")
print(now)
print(value)
while value == now:
time.sleep(1)
print("\nSuccess")
I have implemented in my project and it's working properly. Please have a look on below code.
from django.http import HttpResponse, StreamingHttpResponse
from django.views.decorators.http import condition
import time
#condition(etag_func=None)
def stream(request):
resp = StreamingHttpResponse(stream_response_generator(request))
return resp
def stream_response_generator(request):
start = time.time()
end = start + 60
while start < end:
#Here you can add your method
print ("This is test") # will print after 60 secound after frist executing of time
time.sleep(2) # sleep time added

i keep getting 'my_time' is not defined.I don't understand why

import webbrowser
from datetime import datetime
import time
def open_inTime():
now = datetime.now()
my_time = now.time()
if my_time >= time(14,50) and my_time <= time(16,00):
webbrowser.open("https://www.google.com")
else:
print("Time to open webbrowser is long over due")
open_inTime()
Here is what I think you are trying to achieve:
from datetime import datetime
import time
def open_inTime():
return datetime.now().time()
start_time = datetime.strptime('14:50', '%H:%M').time()
end_time = datetime.strptime('16:00', '%H:%M').time()
if start_time <= open_inTime() <= end_time:
print('Success!')
else:
print("Time to open webbrowser is long over due")
Explanation
In general, use functions to return values.
Define time objects from strings and assign them to variables.
Use chained comparisons as this is more efficient and readable.

Categories

Resources