I want to update my date column with certain times because some of the dates are not correct. For some reason, they key in the date with time between 00:00 and 7:30 with the day before.
For example:
JavaScript
x
6
1
date time
2
0 01-01-2022 01:00
3
1 01-01-2022 20:00
4
2 01-05-2022 03:00
5
2 01-07-2022 06:00
6
Which supposes to be like this:
JavaScript
1
6
1
date time
2
0 01-02-2022 01:00
3
1 01-01-2022 20:00
4
2 01-06-2022 03:00
5
2 01-08-2022 06:00
6
I know I can update all of dates with this code.
JavaScript
1
2
1
df["date"] = pd.to_datetime(df["date"]) + datetime.timedelta(days=1)
2
But I have no idea how to only update certain rows I want.
Does anyone know how to update the date column?
Advertisement
Answer
while the other answers are correct and efficient, i’d like to add the long answer using a for loop and an if statement
JavaScript
1
7
1
for i in range(len(df)):
2
if pd.to_datetime(df["time"][i]) > pd.to_datetime('00:00') and pd.to_datetime(df["time"][i]) < pd.to_datetime("7:30"):
3
df["date"][i] = pd.to_datetime(df["date"][i]) + datetime.timedelta(days=1)
4
5
# this line is to cut he extra time added after the addition operation
6
df['date'][i] = df['date'][i].strftime('%d-%m-%Y') # try to remove it and see for yourself what it does
7
input:
JavaScript
1
5
1
date time
2
0 01-02-2022 01:00
3
1 01-02-2022 01:00
4
2 01-02-2022 11:00
5
output:
JavaScript
1
5
1
date time
2
0 01-03-2022 01:00
3
1 01-03-2022 01:00
4
2 01-02-2022 11:00
5