Python: what's the subtraction value between two time.time()? - python

import time
print time.time() - time.time()
the result unit is millisecond or second?
what I want do is judge if the two operation time span is larger than 10 minutes

Return the time in seconds since the epoch as a floating point number. (from documentation)
So difference between two times is also seconds.
time_a = time.time()
# ... some operations ...
ten_minutes = 10 * 60
time_span = time.time() - time_a
if time_span > ten_minutes:
# time span is larger than 10 minutes.

Related

What's the time unit of this timedelta?

import time
from datetime import timedelta
start = time.time()
...
end = time.time()
print('Total time spent: {}'.format(str(timedelta(seconds=end - start))))
For example, one output could be:
0:00:00.395616
The fist 3 must be hours, minutes and seconds. What about the '.395616' part? Is it millseconds or microseconds, or even seconds?

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}")

why is not the result 00:00:XX?

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

How can I iterate through list data faster using multiprocessing?

I'm trying to determine the amount of time worked by a list of employees during their shift - this data is given to me in the form of a CSV file.
I populate a matrix with this data and iterate through it using a while loop applying the necessary conditionals (for example, deducting 30 minute for lunch). This is then put into a new list, which is used to make an Excel worksheet.
My script does what it is meant to do, but takes a very long time when having to loop through a lot of data (it needs to loop through approximately 26 000 rows).
My idea is to use multiprocessing to do the following three loops in parallel:
Convert the time from hh:mm:ss to minutes.
Loop through and apply conditionals.
Round values and convert back to hours, so that this is not done within the big while loop.
Is this a good idea?
If so, how would I have the loops run in parallel when I need data from one loop to be used in the next? My first thought is to use the time function to give a delay, but then I'm concerned that my loops may "catch up" with one another and spit out that the list index being called does not exist.
Any more experienced opinions would be amazing, thanks!
My script:
import pandas as pd
# Function: To round down the time to the next lowest ten minutes --> 77 = 70 ; 32 = 30:
def floor_time(n, decimals=0):
multiplier = 10 ** decimals
return int(n * multiplier) / multiplier
# Function: Get data from excel spreadsheet:
def get_data():
df = pd.read_csv('/Users/Chadd/Desktop/dd.csv', sep = ',')
list_of_rows = [list(row) for row in df.values]
data = []
i = 0
while i < len(list_of_rows):
data.append(list_of_rows[i][0].split(';'))
data[i].pop()
i += 1
return data
# Function: Convert time index in data to 24 hour scale:
def get_time(time_data):
return int(time_data.split(':')[0])*60 + int(time_data.split(':')[1])
# Function: Loop through data in CSV applying conditionals:
def get_time_worked():
i = 0 # Looping through entry data
j = 1 # Looping through departure data
list_of_times = []
while j < len(get_data()):
start_time = get_time(get_data()[i][3])
end_time = get_time(get_data()[j][3])
# Morning shift - start time < end time
if start_time < end_time:
time_worked = end_time - start_time # end time - start time (minutes)
# Need to deduct 15 minutes if late:
if start_time > 6*60: # Late
time_worked = time_worked - 15
# Need to set the start time to 06:00:00:
if start_time < 6*60: # Early
time_worked = end_time - 6*60
# Afternoon shift - start time > end time
elif start_time > end_time:
time_worked = 24*60 - start_time + end_time # 24*60 - start time + end time (minutes)
# Need to deduct 15 minutes if late:
if start_time > 18*60: # Late
time_worked = time_worked - 15
# Need to set the start time to 18:00:00:
if start_time > 18*60: # Early
time_worked = 24*60 - 18*60 + end_time
# If time worked exceeds 5 hours, deduct 30 minutes for lunch:
if time_worked >= 5*60:
time_worked = time_worked - 30
# Set max time worked to 11.5 hours:
if time_worked > 11.5*60:
time_worked = 11.5*60
list_of_times.append([get_data()[i][1], get_data()[i][2], round(floor_time(time_worked, decimals = -1)/60, 2)])
i += 2
j += 2
return list_of_times
# Save the data into Excel worksheet:
def save_data():
file_heading = '{} to {}'.format(get_data()[0][2], get_data()[len(get_data())-1][2])
file_heading_2 = file_heading.replace('/', '_')
df = pd.DataFrame(get_time_worked())
writer = pd.ExcelWriter('/Users/Chadd/Desktop/{}.xlsx'.format(file_heading_2), engine='xlsxwriter')
df.to_excel(writer, sheet_name='Hours Worked', index=False)
writer.save()
save_data()
You can look at multiprocessing.Pool which allows executing a function multiple times with different input variables. From the docs
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
Then, it's a matter of splitting up your data into chunks (instead of the [1, 2, 3] in the example).
But, my personal preference, is to take the time and learn something that is distributed by default. Such as Spark and pyspark. It'll help you in the long run immensely.

Calculating the times into minutes

I am working on my python code as I want to calulcating on the program time to convert it into minutes. When the program start at 12:00AM and my current time show as 1:00AM. The end time show for the program is 6:00AM, so I want to work out between 1:00AM and 6:00AM to take it away then multiply it by 60 to convert it into minutes.
Example: 6 take away 1 which is 5 then I want to multply it by 60 which it is 300 minutes.
Here is the code:
current_time = int(time.strftime("%M"))
prog_width = self.getControl(int(program_id)).getWidth()
prog_length = int(prog_width) / 11.4 - current_time
prog_length = str(prog_length)
prog_length = prog_length.replace('.0', '')
prog_length = int(prog_length)
print prog_length
Can you please show me an example of how I can calculating between 1:00AM and 6:00AM to take it away then convert it into minutes when multply by 60?
You can use the datetime module
from datetime import timedelta
start = timedelta(hours=1)
end = timedelta(hours=6)
duration = end - start
print duration.total_seconds() / 60

Categories

Resources