How to find the start time and end time of an event in python?

Related searches

I have a data frame consists of column 1 i.e event and column 2 is Datetime:

Sample data

 Event   Time
    0   2020-02-12 11:00:00
    0   2020-02-12 11:30:00
    2   2020-02-12 12:00:00
    1   2020-02-12 12:30:00
    0   2020-02-12 13:00:00
    0   2020-02-12 13:30:00
    0   2020-02-12 14:00:00
    1   2020-02-12 14:30:00
    0   2020-02-12 15:00:00
    0   2020-02-12 15:30:00

And I want to find start time and end time of each event:

Desired Data

 Event  EventStartTime  EventEndTime
    0   2020-02-12 11:00:00 2020-02-12 12:00:00
    2   2020-02-12 12:00:00 2020-02-12 12:30:00
    1   2020-02-12 12:30:00 2020-02-12 13:00:00
    0   2020-02-12 13:00:00 2020-02-12 14:30:00
    1   2020-02-12 14:30:00 2020-02-12 15:00:00

Note: EventEndTime is time when the event changes the value say from value 1 to got change to 0 or any other value or vice versa

Assuming the dataframe is data:

current_event = None
result = []
for event, time in zip(data['Event'], data['Time']):
    if event != current_event:
        if current_event is not None:
            result.append([current_event, start_time, time])
        current_event, start_time = event, time
data = pandas.DataFrame(result, columns=['Event','EventStartTime','EventEndTime'])

The trick is to save your event number; if the next event number is not the same as the saved one, the saved one has to be ended and a new one started.

Measuring elapsed time with the Time module, import time start = time.time() # run your code end = time.time() elapsed = end - the best measure of elapsed time (since Python 3.3), use time.perf_counter() . Use .start() to start it") elapsed_time = time. perf_counter ()-self. _start_time self. _start_time = None if self. logger: self. logger (self. text. format (elapsed_time)) return elapsed_time Instead of using print() directly, you create another instance variable, self.logger , that should refer to a function that takes a string as an argument.

Here is a method that can get the results without a for loop. I assume that the input data is read into a dataframe called df:

# Initialize the output df
dfout = pd.DataFrame()
dfout['Event'] = df['Event']
dfout['EventStartTime'] = df['Time']

Now, I create a variable called 'change' that tells you whether the event changed.

dfout['change'] = df['Event'].diff()

This is how dfout looks now:

   Event       EventStartTime  change
0      0  2020-02-12 11:00:00     NaN
1      0  2020-02-12 11:30:00     0.0
2      2  2020-02-12 12:00:00     2.0
3      1  2020-02-12 12:30:00    -1.0
4      0  2020-02-12 13:00:00    -1.0
5      0  2020-02-12 13:30:00     0.0
6      0  2020-02-12 14:00:00     0.0
7      1  2020-02-12 14:30:00     1.0
8      0  2020-02-12 15:00:00    -1.0
9      0  2020-02-12 15:30:00     0.0

Now, I go on to remove the rows where the event did not change:

dfout = dfout.loc[dfout['change'] !=0 ,:]

This will now leave me with rows where the event has changed.

Next, the event end time of the current event is the start time of the next event.

dfout['EventEndTime'] = dfout['EventStartTime'].shift(-1)

The dataframe looks like this:

   Event       EventStartTime  change         EventEndTime
0      0  2020-02-12 11:00:00     NaN  2020-02-12 12:00:00
2      2  2020-02-12 12:00:00     2.0  2020-02-12 12:30:00
3      1  2020-02-12 12:30:00    -1.0  2020-02-12 13:00:00
4      0  2020-02-12 13:00:00    -1.0  2020-02-12 14:30:00
7      1  2020-02-12 14:30:00     1.0  2020-02-12 15:00:00
8      0  2020-02-12 15:00:00    -1.0                  NaN

You may chose to remove the 'change' column and also the last row if not needed.

How to measure time elapsed in Python?, to start counting time somewhere in my code and then hello" end = timeit. timeit() print end - start. How to get the current time in Python. import time seconds = 1545925769 # returns struct_time t = time.localtime(seconds) print("t1: ", t) # returns seconds from struct_time s = time.mktime(t) print("\s:", seconds) When you run the program, the output will be something like:

Use group by and agg to get the output in desired format.

df =pd.DataFrame([['0',11],['1',12],['1',13],['0',15],['1',16],['3',11]],columns=['Event','Time'] )
df.groupby(['Event']).agg(['first','last']).rename(columns={'first':'start-event','last':'end-event'})

Output:

Event start-event   end-event   
0      11           15
1      12           16
3      11           11

8.1. datetime — Basic date and time types — Python 3.4.10 , For related functionality, see also the time and calendar modules. Example of counting days to an event: >>> implementation) passes a datetime with dt. tzinfo is self. return ZERO assert dt.tzinfo is self # Find start and end times for US DST. time delta() arithmetic is not supported for date time.time() objects; if you need to use offsets from an existing date time.time() object, just use date time.datetime.combine() to form a date time.date time() instance, do your calculations, and 'extract' the time again with the .time() method.

How to write a Python code able to evaluate end time of a period of , The program should return what the time of day would be when the event ends. You'll also have to check the hours for % 24 to make sure you roll the hours over as well. Or please recommend where and how to start learning Python. 104. To measure time elapsed during program's execution, either use time.clock () or time.time () functions. The python docs state that this function should be used for benchmarking purposes.

Python End Date time calculate based start date time and Duration , I would like to calculation End Date based on start date and Duration and working hours and day. For example: start date 01/01/2018 10:00� Python Code: import time def sum_of_n_numbers(n): start_time = time.time() s = 0 for i in range(1,n+1): s = s + i end_time = time.time() return s,end_time-start_time n = 5 print(" Time to sum of 1 to ",n," and required time to calculate is :",sum_of_n_numbers(n)) Sample Output:

Advantages of process_time() : 1. process_time() provides the system and user CPU time of the current process. 2. We can calculate float and integer both values of time in seconds and nanoseconds. 3. Used whenever there is a need to calculate the time taken by the CPU for the particular process.

Comments
  • paste the data in your question and dont link an image
  • How do you distinguish between a start and an end? Are events with the same number guaranteed to not overlap?
  • @Błotosmętek start is when 1st time the event started and end time when the value of event changes to some other value. Check the images of data and desired output data
  • @luigigi pasted
  • Your example makes no sense to me. For example, why 2 1 2020-02-12 **13:00:00** 2020-02-12 13:00:00 if 3 1 2020-02-12 **12:30:00**?
  • hey if I want to group by some category first and then itterate through that loop then what I suppose to do? @Błotosmętek
  • Output not same as expected by op.
  • This is not a desired output.