Home > Software engineering >  How to add days to pandas datetime until x day is met, while keeping the previous date?
How to add days to pandas datetime until x day is met, while keeping the previous date?

Time:05-20

This is what my data currently looks like:

STARTDATE   ENDDATE 
2021-07-16  2023-09-01

I would like to copy the row with the same information while adding plus 1 to the start date until I hit the end date.

What I'm looking to get:

STARTDATE   ENDDATE 
2021-07-16  2023-09-01
2021-07-17  2023-09-01
2021-07-18  2023-09-01
2021-07-19  2023-09-01
......................
2021-08-31  2023-09-01
2021-09-01  2023-09-01

Thanks!

CodePudding user response:

Try this:

df.assign(STARTDATE = [pd.date_range(s,e) for s,e in zip(df['STARTDATE'],df['ENDDATE'])]).explode('STARTDATE')

if your starting df does not have date values, try this first

df = df.apply(pd.to_datetime)

output:

    STARTDATE   ENDDATE
0   2021-07-16  2023-09-01
0   2021-07-17  2023-09-01
0   2021-07-18  2023-09-01
0   2021-07-19  2023-09-01
0   2021-07-20  2023-09-01
... ... ...
0   2023-08-28  2023-09-01
0   2023-08-29  2023-09-01
0   2023-08-30  2023-09-01
0   2023-08-31  2023-09-01
0   2023-09-01  2023-09-01
  • Related