Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading