Why is my python time comparison wrong every minute? - python-3.x

Hello everyone Im making a time comparison project.
Basically what Im trying to do is have my code take a reading of time and then take a separate reading of time, if the system where to go to sleep for any length of time, the code will see that a time difference has occurred.
The problem that Im running into is if statement will trigger every minute with a value of 40 seconds plus the 1 second delay I added and I don't know why.
Any thoughts?
import datetime
import time
while True:
current_time_A = datetime.datetime.now()
print("current time A ",
int(current_time_A.strftime("%H%M%S")))
time.sleep(1)
current_time_B = datetime.datetime.now()
print("current time B ",
int(current_time_B.strftime("%H%M%S")))
time_elapsed = ((int(current_time_B.strftime("%H%M%S"))) - (int(current_time_A.strftime("%H%M%S"))))
print("time_elapsed = ",time_elapsed)
if time_elapsed >= 5:
print("time changed more then 5 seconds")
Here's the output you will get
current time A 1959
current time B 2000
time_elapsed = 41
time changed more then 5 seconds
current time A 2000
current time B 2001
1
current time A 2001

So the problem you're facing is due to how you're setting everything up. Basically, you're getting the 2 times' hour, minute, and second as a string, converting them to an int, and then subtracting their differences. Seconds only go up to 59 before going back to 00. So, when current_time_A's second is 59 and current_time_B's second is 00, the difference comes out to be 41 (because the minute changes as well).
Instead of converting back and forth between types (datetime.datetime -> str -> int), I suggest using time.time() to get the timestamp and do your calculations on that:
import time
while True:
current_time_A = time.time()
print(f"Current time A {current_time_A}")
time.sleep(1)
current_time_B = time.time()
print(f"Current time B: {current_time_B}")
# calculate how many seconds have elapsed since the start of the program
elapsed_time = current_time_B - current_time_A
print(f"Elapsed time: {elapsed_time}")
# round to the nearest second
print("Elapsed time (rounded):", round(elapsed_time))

Related

I want to count time as code runs and after 5 sec i want to print number which is in loop but why my code is not working for time.time()?

It takes numbers of range 10000 and in every 5 sec it print the number. I dont know why its not working
import time
start=time.time()
for i in range(10000):
if(int(time.time()-start)==5):
print('Hello ',i)
time.sleep(3)
start=time.time()
I tested your code locally, and I don't think there's anything wrong with it. The reason you do not see any print is because the whole for loop runs in less than 5 seconds. Please try changing to a bigger value.
It might also help to have another variable equal to the value of the very first start value (timeInitial) and then add the following at the end of the code, after the for loop.
print (f'Total time: {int(time.time() - timeInitial)}')
When having for i in range(10000): the value printed is "Total time: 0". Increase the range to 20000000 and I got Hello 15107775 and Total time: 9. Your values may differ.
Just change time.sleep(3) to time.sleep(5) and move it out of the if block
import time
start=time.time()
for i in range(10000):
if(int(time.time()-start)==5):
print('Hello ',i)
start=time.time()
time.sleep(5)

Duration Calculator in Python

I have been studying Python by myself since a month ago.
I want to make a duration calculator that shows the total time of each different duration.
For instance, there are two different flights I have to take, and I want to get the total time I would be in the airplanes. It goes like this.
a = input('Enter the duration: ') #11h40m
b = input('Enter the duration: ') #13h54m
#it may show the total duration
01d01h34m
Try this :
Edit : I tried to use strftime to format the 'duration' but had some issues with day.
So I did it manually (you can format it the way you wish)
import datetime
import time
# Convert str to strptime
a_time = datetime.datetime.strptime("11h40m", "%Hh%Mm")
b_time = datetime.datetime.strptime("13h54m", "%Hh%Mm")
# Convert to timedelta
a_delta = datetime.timedelta(hours = a_time.hour,minutes=a_time.minute)
b_delta = datetime.timedelta(hours = b_time.hour,minutes=b_time.minute)
duration = (a_delta + b_delta)
print(str(duration.days) + time.strftime('d%Hh%Mm', time.gmtime(duration.seconds)))
'1d01h34m'

Find date upon which defined age in seconds is reached

I am attempting to write a program that
takes a certain number of seconds (say 1000000000), then
takes a given date (for example one's birthday) and
then determines when (at which given date) this age in number of seconds has been reached.
Certainly, the program should recognize if that age in number of seconds is in the past.
But even before building a check for this, the code runs into problems.
After receiving error message I tried changing parameter name from month to umonth in the input stage. That brought no difference.
from datetime import datetime
seconds = int(input("seconds: "))
year = int(input("year: "))
month = int(input("month: "))
day = int(input("day: "))
#Calculate time in seconds between now and the day of birth
date = (datetime(year=year, month=month, day=day) - datetime(seconds)).total_seconds()
print("You will be {} seconds old on {} old.".format(seconds, date))
I am still dabbling with the datetime library.
I received a TypeError from python3.
"TypeError: Required argument 'month' (pos 2) not found"
Edit:
Following suggestions in the comments, I modified the code for using a new method, to convert a date into seconds.
from datetime import datetime
#seconds = int(input("seconds: "))
seconds = 1000000000
#year = int(input("year: "))
#month = int(input("month: "))
#day = int(input("day: "))
year = 1987
month = 9
day = 11
date = datetime.datetime(year,month,day)
#Calculate time in seconds between now and the day of birth
(date.total_seconds(datetime(year=year, month=month, day=day)) - seconds)
print("You will be {} seconds old on {} old.".format(seconds, date))
That yields an AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
I am aware I dont know exactly how to use datetime library.
Working through the docs to understand.
But still, those things seem trivial to achieve.
Perhaps someone can explain.
The goal is, as before, to take a number of seconds and a date of birth.
And to see when, from the date of birth on, the number of seconds will be reached.
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
You are receiving the above error because you already used import datetime. No need of writing datetime.datetime. You can directly use datetime(year, month, day).

Reduce execution time when parsing files

I need to write a script in python2.7 which parse 4 files.
I need to be fast as possible.
For the moment i create a loop, and i parse the 4 files one after another.
I need to understand one thing. If a created 4 parsing script programs (one for each file) and launch the 4 script in 4 different terminal, is this going to reduce the execution time (or not) ?
Thx,
if you ave a potato pc , Yes it will Reduce the Execution Time
i suggest yu to use multithreading on every script for up the speed
import threading
import time
def main():
starttime = time.time()
endtime = time.time()
for x in range(1,10000): # For Print 10000 Times The Character X For Try If It Reduce Or Nop
print x
print "Time Speled : " + round((endtime-starttime), 2) # For Show The Time
threads = []
t = threading.Thread(target=main)
threads.append(t)
t.start()
and you can Try the difference with threading and without it

Count down to a week later from current date and time in Python?

I want to make an app that when run, it will get the current date and time from the user's computer, and then count down to a week later at the time of running.
So for example:
The user runs the app on 06-06-2017 11:00:00, it must do a count down to a deadline a week later and display the deadline date and time, and show a count down of how many days, hours, minutes and seconds are left.
EDIT:
So far I have only been able to get the date and time and the time increments normally per second. I am having difficulty decrementing it. Without the last line of the code the time decrements but does not update automatically. I have yet to find a way to perform a count down from a week in advance.
def updateTime():
X = 1
t = datetime.datetime.now()
s = t.replace(microsecond=0)
result = s - datetime.timedelta(seconds=X)
future = s + datetime.timedelta(days=7, hours=0, minutes=0, seconds=0)
lblTime.configure(text=result, font=("", 14))
lblTime.after(100, updateTime)
You definitely want to calculate the target time only once instead of getting it every time the updateTime handler runs. Furthermore, you can simply do arithmetic on datetime objects to get a timedelta object back which you can then display in your GUI.
Here is an example that is printing the output to the console. You can probably adjust this as needed to make it display in your GUI.
import datetime
target_time = datetime.datetime.now() + datetime.timedelta(days=7)
target_time = target_time.replace(microsecond=0)
def get_remaining_time():
delta = target_time - datetime.datetime.now()
hours = delta.seconds // 3600
minutes = (delta.seconds % 3600) // 60
seconds = delta.seconds % 60
print('{} days, {} hours, {} minutes, {} seconds'.format(delta.days, hours, minutes, seconds))
while True:
get_remaining_time()

Resources