I have a dataframe that it has a datetime column 'started_at'
started_at |
---|
2019-12-03 10:33:06 |
2019-12-03 12:29:37 |
2019-12-03 18:29:37 |
2019-12-04 11:29:37 |
I would like to change the time to it, if the time is smaller that a specific time (12:00)
So, the data should become:
started_at |
---|
2019-12-03 12:00:00 |
2019-12-03 12:29:37 |
2019-12-03 18:29:37 |
2019-12-04 12:00:00 |
Any suggestions?
CodePudding user response:
Maybe you can try this
import datetime as dt
for i in range(len(df)):
fmt = '%Y-%m-%d %H:%M:%S'
val = dt.datetime.strptime(str(df.loc[i][0]), fmt )
new_val = dt.datetime.strptime(str(df.loc[i][0]).split(" ")[0] " 12:00:00", fmt )
if val < new_val:
df["started_at"] = df["started_at"].replace(val,new_val)
CodePudding user response:
I would first apply a mask for your times under '12':
mask=df["started_at"].dt.hour<12
Then I would modify the values according to that mask:
df[mask]=df['started_at'].dt.strftime("%Y-%m-%d 12:00:00")