I have a data frame with the DateTime index. I want to find the difference between row datetimes and convert it into seconds. My code:
import datetime df = index Col_A datetime 2019-10-01 08:10:53 400.5334 2019-10-01 08:10:53 2019-10-01 08:10:57 401.2720 2019-10-01 08:10:57 2019-10-01 08:10:59 401.7874 2019-10-01 08:10:59 2019-10-01 08:11:02 402.1579 2019-10-01 08:11:02 2019-10-01 08:11:06 402.6045 2019-10-01 08:11:06 df['timedif'] = df['datetime'].diff() df['timedif1'] = df['timedif'].total_seconds()
Present output:
print(df['timedif']) 2019-10-01 08:10:53 NaT 2019-10-01 08:10:57 0 days 00:00:04 2019-10-01 08:10:59 0 days 00:00:02 2019-10-01 08:11:02 0 days 00:00:03 2019-10-01 08:11:06 0 days 00:00:04 Name: datetime, Length: 1604993, dtype: timedelta64[ns] AttributeError: 'Series' object has no attribute 'total_seconds'
How do I convert the timedif
column into total seconds?
Advertisement
Answer
Simply do:
df['timedif1'] = df['timedif'] / np.timedelta64(1, 's')
Example:
df = pd.DataFrame({'datetime':[datetime.datetime(2019,10,1,8,10,53), datetime.datetime(2019,10,1,8,10,57), datetime.datetime(2019,10,2,8,10,57)]}) df['timedif'] = df['datetime'].diff() df['timedif1'] = df['timedif'] / np.timedelta64(1, 's')
datetime timedif timedif1 0 2019-10-01 08:10:53 NaT NaN 1 2019-10-01 08:10:57 0 days 00:00:04 4.0 2 2019-10-02 08:10:57 1 days 00:00:00 86400.0