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 (
Screenshot (2):
CodePudding user response:
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