Error in replacing 'hour' and 'minute' of pandas TimeStamp

Question:

I’m creating a datetime variable with pandas using pd.to_datetime()
The referenced dataframe only has the date (e.g. 31/12/2023) so the function returns it with time 00:00:00 (e.g. 31/12/2023 00:00:00) and now I want to set the time value individually with the replace() function following the examples shown in these two SO posts (ex1, ex2), but that leads to an error: TypeError: replace() got an unexpected keyword argument ‘hour’

Here is the code:

end = pd.to_datetime(df_end_date, dayfirst=True).replace(hour=23, minute=59)

The expression df_end_date has a single value, see screenshot (1) below or here.

The complete error message is shown in screenshot (2) below or here.

Screenshot (1):

enter image description here

enter image description here

Screenshot (2):

enter image description here

Asked By: Dattel Klauber

||

Answers:

If df_end_date is scalar, solution working:

df_end_date = '31/12/2023'

end = pd.to_datetime(df_end_date, dayfirst=True).replace(hour=23, minute=59)
print (end)
2023-12-31 23:59:00

If Series, here one element Series need:

df_end_date = pd.Series(['31/12/2023'])
print (df_end_date)
0    31/12/2023
dtype: object

end = pd.to_datetime(df_end_date, dayfirst=True) + pd.offsets.DateOffset(hour=23, minute=59)
print (end)
0   2023-12-31 23:59:00
dtype: datetime64[ns]

Or:

end = pd.to_datetime(df_end_date, dayfirst=True).map(lambda x: x.replace(hour=23,minute=59))
print (end)
0   2023-12-31 23:59:00
dtype: datetime64[ns
Answered By: jezrael
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.