I have a dataframe with a number of datetime values. I'd like to change the time portion of these to a specific time that is the same for all observations in the dataframe, but preserve the date portion of the datetime.
I can do this with a single datetime, using the datetime package and the .replace() function:
import datetime
dt_test=datetime.datetime(2020, 5, 17,21,30,15)
print(dt_test)
dt_test=dt_test.replace(hour=6,minute=0,second=0)
print(dt_test)
Which returns:
2020-05-17 21:30:15
2020-05-17 06:00:00
I feel like I should be able to use the .dt operator to apply this to the whole column, but receive an error when I attempt to do so.
import pandas as pd
dates=[
datetime.datetime(2018,1,1,4,30,15),
datetime.datetime(2018,1,2,4,30,15),
datetime.datetime(2018,1,3,4,30,15),
datetime.datetime(2018,1,3,6,0,0),
datetime.datetime(2018,1,3,12,30,15),
datetime.datetime(2018,1,1,4,30,15),
datetime.datetime(2018,1,2,4,30,15),
datetime.datetime(2018,1,4,4,30,15),
datetime.datetime(2018,1,2,12,30,15),
datetime.datetime(2018,1,4,12,30,15),
]
ids=list(range(len(dates)))
df=pd.DataFrame(zip(ids,dates),columns=['id','date_time'])
df
Returns:
id date_time
0 0 2018-01-01 04:30:15
1 1 2018-01-02 04:30:15
2 2 2018-01-03 04:30:15
3 3 2018-01-03 06:00:00
4 4 2018-01-03 12:30:15
5 5 2018-01-01 04:30:15
6 6 2018-01-02 04:30:15
7 7 2018-01-04 04:30:15
8 8 2018-01-02 12:30:15
9 9 2018-01-04 12:30:15
Where the 'date_time' column is dtype: datetime64[ns], as desired (see this question).
I then attempt to use pandas' .replace() function with the .dt operator:
df['date_time'].dt.replace(hour=6,minute=0,second=0)
df
But I receive the following error (using jupyter, if that matters):
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-13-65a7bb8c3365> in <module>
----> 1 df['date_time'].dt.replace(hour=6,minute=0,second=0)
2 df
AttributeError: 'DatetimeProperties' object has no attribute 'replace'
How can I go about efficiently replacing the time portion of a datetime variable in a pandas column?
Note: I found this question that can set the time to midnight for all dates, but the time does matter for me and is unlikely to be midnight.
