I have a pandas dataframe time column like following.
segments_data['time']
Out[1585]:
0 04:50:00
1 04:50:00
2 05:00:00
3 05:12:00
4 06:04:00
5 06:44:00
6 06:44:00
7 06:47:00
8 06:47:00
9 06:47:00
I want to add 5 hours and 30 mins to above time column. I am doing following in python.
pd.DatetimeIndex(segments_data['time']) + pd.DateOffset(hours=5,minutes=30)
But it gives me an error.
TypeError: object of type 'datetime.time' has no len()
please help.
as of '0.25.3' this is as simple as
df[column] = df[column] + pd.Timedelta(hours=1)
You can try importing timedelta
:
from datetime import datetime, timedelta
and then:
segments_data['time'] = pd.DatetimeIndex(segments_data['time']) + timedelta(hours=5,minutes=30)
Pandas does not support vectorised operations with datetime.time
objects. For efficient, vectorised operations, there is no requirement to use the datetime
module from the standard library.
You have a couple of options to vectorise your calculation. Either use a Pandas timedelta
series, if your times represent a duration. Or use a Pandas datetime
series, if your times represent specific points in time.
The choice depends entirely on what your data represents.
timedelta
seriesdf['time'] = pd.to_timedelta(df['time'].astype(str)) + pd.to_timedelta('05:30:00')
print(df['time'].head())
0 10:20:00
1 10:20:00
2 10:30:00
3 10:42:00
4 11:34:00
Name: 1, dtype: timedelta64[ns]
datetime
seriesdf['time'] = pd.to_datetime(df['time'].astype(str)) + pd.DateOffset(hours=5, minutes=30)
print(df['time'].head())
0 2018-12-24 10:20:00
1 2018-12-24 10:20:00
2 2018-12-24 10:30:00
3 2018-12-24 10:42:00
4 2018-12-24 11:34:00
Name: 1, dtype: datetime64[ns]
Notice by default the current date is assumed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With