Reputation: 480
I have hours extracted from the timestamp of my dataframe by the command lines:
import pandas as pd
from datetime import *
from datetime import datetime
import datetime as dt
import time
df['timestamp'] = pd.to_datetime(df['timestamp'])
df['time'] = df['timestamp'].dt.time
df['time']
Output: id time
3539 23:49:58
3540 23:52:39
3541 23:55:19
3542 23:58:00
Name: time, dtype: object
I need to convert time column into seconds, i.e. 23:49:58 = 23*3600+49*60+58 = 85798 seconds
id time
3539 85798
Thanks a lot
Upvotes: 2
Views: 4514
Reputation: 862611
Convert datetimes to hour
s, minute
s and second
s:
df['time'] = df['timestamp'].dt.hour * 3600 +
df['timestamp'].dt.minute * 60 +
df['timestamp'].dt.second
Or to_timedelta
and get total_seconds
:
df['time'] = pd.to_timedelta(df['timestamp'].dt.strftime('%H:%M:%S'))
.dt.total_seconds().astype(int)
Sample:
df = pd.DataFrame({'timestamp':['2015-04-01 23:49:58','2016-04-01 23:49:58']})
df['timestamp'] = pd.to_datetime(df['timestamp'])
print (df)
timestamp
0 2015-04-01 23:49:58
1 2016-04-01 23:49:58
df['time1'] = df['timestamp'].dt.hour * 3600 + \
df['timestamp'].dt.minute * 60 + \
df['timestamp'].dt.second
df['time2'] = (pd.to_timedelta(df['timestamp'].dt.strftime('%H:%M:%S'))
.dt.total_seconds().astype(int))
print (df)
timestamp time1 time2
0 2015-04-01 23:49:58 85798 85798
1 2016-04-01 23:49:58 85798 85798
Upvotes: 2