使用条件设置日期时间列的时间

Set the time of datetime column with condition

我有一个数据框,它有一个日期时间列 '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

如果时间小于特定时间 (12:00),我想更改时间

所以,数据应该变成:

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

有什么建议吗?

我会先为你'12'以下的时间敷面膜:

mask=df["started_at"].dt.hour<12

然后我会根据那个掩码修改值:

df[mask]=df['started_at'].dt.strftime("%Y-%m-%d 12:00:00")

也许你可以试试这个

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)