I want to find out the charging duration between when the loop finds its first value of '1' and the last value of '1' it detects. I figured out how to find out the duration between 2 timings, but i am unsure of where i can put the 'timestamp' variable.
Here is my current code
from datetime import datetime
#Duration loop
date_format_str = '%H:%M:%S %p'
foundEnd = False
for i in range(len(dfDur01Mar22)):
#only display bus 'SG3079S'
if dfDur01Mar22.iloc[i,1] == 'SG3079S':
#print 'end' when first '0' appears
if not foundEnd and dfDur01Mar22.iloc[i,2] == 0:
print('end')
foundEnd = True
#prints the first time its 0
timestamp = dfDur01Mar22.DateTime[i]
#print(timestamp + " first")
#if charging type is 1
elif dfDur01Mar22.iloc[i,2] == 1:
print(dfDur01Mar22.iloc[i,0],dfDur01Mar22.iloc[i,1],dfDur01Mar22.iloc[i,2])
foundEnd = False
timestamp_2 = dfDur01Mar22.DateTime[i]
#print(timestamp_2 + "last")
#Duration between the first '1' and the last '1' detected
given_time = datetime.strptime(timestamp, date_format_str)
given_time2 = datetime.strptime(timestamp_2, date_format_str)
total = given_time2 - given_time
#print(total)
and here is the values that i need to find the duration from
You need 2 variables like start_time, end_time. after your loop you can calculate this duration.
So new concept of your code is like below. FOUND_1_SITUATION
is your '1' condition in your loop.
from datetime import datetime
#Duration loop
date_format_str = '%H:%M:%S %p'
foundEnd = False
start_time = False
end_time = False
for i in range(len(dfDur01Mar22)):
if FOUND_1_SITUATION and not start_time:
start_time = dfDur01Mar22.DateTime[i]
else :
end_time = dfDur01Mar22.DateTime[i]
duration_between_start_end = end_time - start_time
It means whenever your loop is on '1' condition start_time
will be initialized once. in other conditions end_time
will be updated till end of loop.
After all, you can put duration_between_start_end
calculation below your loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.