why is not the result 00:00:XX? - python

i expected like 00:00:0X but 09:00:0X came out how can i do to make 00:00:0X
import time
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
result = time.localtime(count - begin)
print(count - begin)
print(time.strftime('%I:%M:%S', result))
result:
1.0102884769439697
09:00:01
2.0233511924743652
09:00:02
3.0368154048919678

time.time() will give you the number of seconds since 1.1.1970 in UTC.
So begin is a huge number and count will also be a huge number + about 1. Subtracting those will give about 1.
If you pass this to time.time() you'll get 1.1.1970 plus 1 second. Converting to local time (time.localtime()) will give you whatever timezone offset you are. Obviously +9 hours.
What you probably wanted is time.gmtime() and output in 24 hour format. This will work...
import time
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
result = time.gmtime(count - begin)
print(count - begin)
print(time.strftime('%H:%M:%S', result))
but it is semantically incorrect. If you subtract 2 dates, the result is a timespan, not a date. What is the difference?
If someone asks, how old you are, you have a look at the current year and you subtract the year of your birth. Then you say "I'm 25 years old". You don't add 1.1.1970 and say "I'm 1995 years old".
So the following is semantically much better:
import time
from datetime import timedelta
start = input("Enter를 누르면 타이머를 시작합니다.")
begin = time.time()
while True:
time.sleep(1)
count = time.time()
timespan = timedelta(seconds=count - begin)
print(timespan)

It shows 09:00:00 because you're in the UTC+9 timezone. For example, I'm in UTC+1 (France) and it shows 01:00:00 for me. Therefore, your code will have different outputs depending on where you run it.
To remove this timezone constraint, simply use datetime.timedelta:
begin = time.time()
while True:
time.sleep(1)
count = time.time()
print(datetime.timedelta(seconds=round(count - begin)))
Output:
0:00:01
0:00:02
0:00:03
0:00:04
0:00:05

Related

How to find the difference between two times

I'm trying to figure out a way to take two times from the same day and figure out the difference between them. So far shown in the code below I have converted both of the given times into Int Vars and split the strings to retrieve the information. This works well but when the clock in values minute is higher than the clock out value it proceeds to give a negative value in minute slot of the output.
My current code is:
from datetime import datetime
now = datetime.now()
clocked_in = now.strftime("%H:%M")
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
hours = out_hh - in_hh
mins = out_mm - in_mm
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
if the clocked in value is 12:30 and the clocked out value is 18:10
the output is:
6:-20
the output needs to be converted back into a stand time format when everything is done H:M:S
Thanks for you assistance and sorry for the lack of quality code. Im still learning! :D
First, in order to fix your code, you need to convert both time to minutes, compute the difference and then convert it back to hours and minutes:
clocked_in = '12:30'
clocked_out = '18:10'
def calc_total_hours(clockedin, clockedout):
in_hh, in_mm = map(int, clockedin.split(':'))
out_hh, out_mm = map(int, clockedout.split(':'))
diff = (in_hh * 60 + in_mm) - (out_hh * 60 + out_mm)
hours, mins = divmod(abs(diff) ,60)
return f"{hours}:{mins}"
print(calc_total_hours(clocked_in, clocked_out))
# 5: 40
Better way to implement the time difference:
import time
import datetime
t1 = datetime.datetime.now()
time.sleep(5)
t2 = datetime.datetime.now()
diff = t2 - t1
print(str(diff))
Output:
#h:mm:ss
0:00:05.013823
Probably the most reliable way is to represent the times a datetime objects, and then take one from the other which will give you a timedelta.
from datetime import datetime
clock_in = datetime.now()
clock_out = clock_in.replace(hour=18, minute=10)
seconds_diff = abs((clock_out - clock_in).total_seconds())
hours, minutes = seconds_diff // 3600, (seconds_diff // 60) % 60
print(f"{hours}:{minutes}")

Start and stop a Python script at a specific time

I am writing a script which will record the user activity in a certain period of time every day. The periods are taken from a JSON response of an API, like this:
[{"working_day": "mon", "work_start_at": "09:00", "work_end_at": "18:00"},
{"working_day": "tue", "work_start_at": "09:00", "work_end_at": "15:00"}]
Let's assume that I can parse these strings in a datetime() format.
I want to run my function accordingly to these periods and stop my function after "work_end_at". I found numerous example of how to run after certain amount of seconds, how to run every day (Python lib schedule) and examples with bash crontab. But nothing of this works for me, because all I want is to start the script at a specific time and stop at a specific time. And then, run again when the next "shift" comes.
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
If I've understood what you're asking, you could use while loops. Have it periodically check the current time with the times for the shift beginning and end. Below is a guide of what I mean, but I'm not sure the comparisons will work.
from time import sleep
def start():
time_periods = working_periods_table.find_all()
today = datetime.datetime.now().isoweekday()
for day in time_periods:
if day["day"] == today:
start_time = day["work_start_at"]
end_time = day["work_end_at"]
while True:
if datetime.datetime.now() >= start_time:
while True:
schedule.every().week.at(start_time).do(record_activity(idle_time=300))
if datetime.datetime.now() >= end_time:
break
break
else:
sleep(100)
I have some way to start my process at certain time but can not stop at certain time, I think you might means after running at 1 hour, even it is not finished yet, still stop the program. in this case you might can use while loop
take a look with my scripts first this might helpful
import time
from time import strftime, localtime
import datetime
now = datetime.datetime.now()
year = int(now.strftime("%Y"))
month = int(now.strftime("%m"))
day = int(now.strftime("%d"))
hour = int(now.strftime("%H"))
start_time_t = datetime.datetime(year=year, month=month, day=day, hour=22, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
if waiting_time >= 0:
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
else:
start_time_t = datetime.datetime(year=year, month=month, day=day + 1, hour=00, minute=0, second=0)
waiting_time = time.mktime(start_time_t.timetuple()) - time.time()
print('the program will be start after ' + time.strftime("%H hours and %M minutes", time.gmtime(waiting_time)))
time.sleep(waiting_time)
It will runs my program every day at 10:00 PM, if pass 10:00 PM the program will runs on the beginning of text day.
If you want to run your script at specific time intervals, I will suggest the code below which I have used on my own script. So simple to implement.
import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)
# 2015 5 6 8 53 40
while True:
now = datetime.datetime.now()
if 14 <= now.hour and 23=> now.hour:
# put your code here
Note that in this piece of code I consider 2 PM until 11 PM. And more important you have to get the current hour persistently in a loop.
If you have a specific day in your mind get your current day out of the loop and compare it to your get value !! It works for me.

How Do I Keep Total Time with Multiple Duplicate Entries?

I will attach my code, but basically I am importing a csv file with start times/end times for picking cases of a particular item. All the cases go to a "cart", which is identified by an ID number. I want to find the total time to pick all the cases. The format of the time is hh:mm:ss and, initially, I was using the datetime module but I could not figure out the documentation, so I ended up just converting all the times to seconds, subtracting end/start for each case, and adding that duration to the total time. In the end, converted total time to hours. Already had number of cases picked total, and divided by total time in hrs to get cases picked per hr. Is this correct logic? I got a number that was very, very low: 7.99 cases/hr, which leads me to believe my timing/duration code is incorrect (already checked that quantity was correct).
#instantiate totalTime to zero
totalTime = 0
#every line/row in file; assume already opened above
for line in lines:
#if there is a different case to pick, find the start time
if taskId != entryList[0]: #this is so it doesnt duplicate times
timestart = entryList[7]
colonStartIndex = timestart.find(":")
hourstart = int(timestart[0:colonStartIndex])
minutestart = int(timestart[colonStartIndex+1:colonStartIndex+3])
colonStartIndex2 = timestart.find(":", colonStartIndex+1)
secondstart = int(timestart[colonStartIndex2 +1:colonStartIndex2 +3])
start = hourstart*3600 + minutestart*60 + secondstart
#start = datetime(year=1, month=1, day=1,hour=hourstart,minute=minutestart,second=secondstart)
#start = datetime.time(start)
timeend = entryList[9]
colonEndIndex = timeend.find(":")
hourend = int(timeend[0:colonEndIndex])
minuteend = int(timeend[colonEndIndex+1:colonEndIndex+3])
colonEndIndex2 = timeend.find(":", colonEndIndex+1)
secondend = int(timeend[colonEndIndex2+1:colonEndIndex2+3])
end = hourend*3600 + minuteend*60 + secondend
#end = datetime(year=1,month=1,day=1,hour=hourend,minute=minuteend,second=secondend)
#end = datetime.time(end)
#duration = datetime.combine(date.today(), end) - datetime.combine(date.today(), start)
duration = end - start
if duration >= 0:
duration = duration
elif duration < 0:
duration = -1*duration
totalTime = totalTime + duration
taskId = entryList[0] #first entry in csv file of each line is cartID
totalTime = totalTime/3600
print(totalTime)
print(quantityCount)
avgNumCases = quantityCount/totalTime
print(avgNumCases)
Thank you so much for any help!! Also, I included the datetime stuff, commented out, so if you could suggest a solution based on that, I am open to it:) I was just frustrated because I spent a good bit of time trying to figure it out, but I'm not super familiar w it and the documentation is pretty hard to understand (esp b/c datetime objects, blah blah)
There is an obvious problem in this section:
duration = end - start
if duration >= 0:
duration = duration
elif duration < 0:
duration = -1*duration
If your start point is 22:00:00 and end point is 21:00:00 your duration will be 1 hour instead of 23 hours.

Seconds left to HH:MM

I need to check how many seconds are lef to the nearest HH:MM time in Python (in 24 hour format). For example, now is 10:00 - I need to check 16:30 same day.
If its 18:00 I need to check secods left to the 16:30 next day end so on.
You probably want to use the datetime module, timeldelta is your friend here:
import datetime
def cal_delta_to(hour, minute):
now = datetime.datetime.now()
target = datetime.datetime(*now.timetuple()[0:3], hour=16, minute=30)
if target < now: # if the target is before now, add one day
target += datetime.timedelta(days=1)
diff = now - target
return diff.seconds
Start with simple steps. Programming is usually about breaking down tasks like these into steps.
Get current time. Get next 16:30. Subtract.
# use datetime
from datetime import datetime, timedelta
# get current time
curr = datetime.now()
# create object of nearest 16:30
nearest = datetime(curr.year, curr.month, curr.day, 16, 30)
# stupidly check if it's indeed the next nearest
if nearest < curr:
nearest += timedelta(days=1)
# get diff in seconds
print (nearest - curr).seconds
If your format is ensured, you can easily calculate the seconds of the day:
def seconds_of_day(hhmm):
return int(hhmm[:2])*3600 + int(hhmm[3:])*60
Having done this the comparison is straightforward:
t1 = seconds_of_day('16:30')
t2 = seconds_of_day('10:00')
#t2 = seconds_of_day('18:01')
diff = 86400-t2+t1 if t1<t2 else t1-t2
Use datetime:
import datetime
func = lambda s: datetime.datetime.strptime(s, '%H:%M')
seconds = (func(s2)-func(s1)).seconds
You can always get what you want, even in the special 'next day' cases, like in case1 below;
# case1: now is '09:30', check seconds left to the 09:29 next day
>>> (func('09:29')-func('09:30')).seconds
86340
# case2: now is '09:30', check 10:30 the same day
>>> (func('10:30')-func('09:30')).seconds
3600

Calculate time between time-1 to time-2?

enter time-1 // eg 01:12
enter time-2 // eg 18:59
calculate: time-1 to time-2 / 12
// i.e time between 01:12 to 18:59 divided by 12
How can it be done in Python. I'm a beginner so I really have no clue where to start.
Edited to add: I don't want a timer. Both time-1 and time-2 are entered by the user manually.
Thanks in advance for your help.
The datetime and timedelta class from the built-in datetime module is what you need.
from datetime import datetime
# Parse the time strings
t1 = datetime.strptime('01:12','%H:%M')
t2 = datetime.strptime('18:59','%H:%M')
# Do the math, the result is a timedelta object
delta = (t2 - t1) / 12
print(delta.seconds)
Simplest and most direct may be something like:
def getime(prom):
"""Prompt for input, return minutes since midnight"""
s = raw_input('Enter time-%s (hh:mm): ' % prom)
sh, sm = s.split(':')
return int(sm) + 60 * int(sh)
time1 = getime('1')
time2 = getime('2')
diff = time2 - time1
print "Difference: %d hours and %d minutes" % (diff//60, diff%60)
E.g., a typical run might be:
$ python ti.py
Enter time-1 (hh:mm): 01:12
Enter time-2 (hh:mm): 18:59
Difference: 17 hours and 47 minutes
Here's a timer for timing code execution. Maybe you can use it for what you want. time() returns the current time in seconds and microseconds since 1970-01-01 00:00:00.
from time import time
t0 = time()
# do stuff that takes time
print time() - t0
Assuming that the user is entering strings like "01:12", you need to convert (as well as validate) those strings into the number of minutes since 00:00 (e.g., "01:12" is 1*60+12, or 72 minutes), then subtract one from the other. You can then convert the difference in minutes back into a string of the form hh:mm.

Categories

Resources