简体   繁体   中英

error in converting string datetime into proper datetime format and calculate total seconds from HH:MM:SS.sss time part in pandas dataframe

I have a pandas dataframe which has date time stamp in string format as follows:

df = pd.DataFrame({'date_time':['2019-06-19 02:10:52.563', '2019-06-20 06:20:35.123', '2019-06-21 15:38:24.567', '2019-06-22 13:45:56.243', '2019-06-23 09:37:34.789']})

What I want to do is to :

  1. change the format to proper date time type
  2. Create a new column that will have total of seconds calculated in round number, eg in the first record total of seconds for 02:10:52.563 will be '7853' seconds (because 52.567 seconds should be taken as 53 seconds.

What I am trying to do:

df['proper_date_time'] = pd.to_datetime(df['date_time'])

It worked fine.

But How to calculate the total seconds?

I tried to do this:

 df['proper_end_date'].dt.time.sub(df['proper_start_date'].dt.time)

But it gave me error:

 TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I also tried:

 (df['proper_end_date'] - df['proper_start_date']).dt.time

This also gave error as:

  AttributeError: 'TimedeltaProperties' object has no attribute 'time'

IIUC add another convert with to_timedelta

pd.to_timedelta(pd.to_datetime(df['date_time']).dt.time.astype(str)).dt.total_seconds()
0     7852.563
1    22835.123
2    56304.567
3    49556.243
4    34654.789
Name: date_time, dtype: float64

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM