Calculate the difference between two dates if both are present in the pandas DataFrame

I currently have various temporary columns (DateTime format) in a pandas DataFrame, as shown below:

Entry Time          Exit Time
00:30:59.555        06:30:59.555
00:56:43.200        
10:30:30.500        11:30:30.500

I would like to return the difference between these times (Exit Time - Entry Time) in a new column in the data frame if both the entry and exit times are present. Otherwise, I would like to skip the line as shown below:

Entry Time          Exit Time          Time Difference
00:30:59.555        06:30:59.555       06:00:00.000
00:56:43.200        
10:30:30.500        12:00:30.500       01:30:00.000

I'm new to Python, so I apologize if this is an obvious question. Any help would be greatly appreciated!

+4
source share
1 answer

If your dtypes is really datetime, then it's really simple:

In [36]:

df['Difference Time'] = df['Exit Time'] - df['Entry Time']
df
Out[36]:
                  Entry Time                  Exit Time  Difference Time
0 2014-08-01 00:30:59.555000 2014-08-01 06:30:59.555000         06:00:00
1 2014-08-01 00:56:43.200000                        NaT              NaT
2 2014-08-01 10:30:30.500000 2014-08-01 11:30:30.500000         01:00:00

[3 rows x 3 columns]

, , pd.to_datetime .

df['Entry time'] = pd.to_datetime(df['Entry Time'])

, , , , , :

df.dropna()['Exit_Time'] - df.dropna()['Entry_Time']
+2

All Articles