Mr.Riply
Mr.Riply

Reputation: 845

Pandas date-time - adding / subtracting (days, months, years)

how can i add N number of months to each pandas date range?

the reason i need this is because I have a list of csv files with the following naming convention:

2013-09-18.csv
2013-10-16.csv
2013-11-20.csv
2013-12-18.csv

and for each date in the below pandas date range, I need to check if the corresponding file exists (date + 4 months) in the following logic.

if todays date is the following:

Date 2013-06-16 (days dont matter)

then I need to check if the following file exists (Date + 4 months):

2013-10-16.csv

and then "do stuff"

I have tried a few approaches including below ones, but without success.

import pandas as pd

datelist = pd.date_range(pd.datetime(year = 2012, month = 6, day = 15), pd.datetime.today()).tolist()
df = pd.DataFrame(datelist)

#print(df.head())

for date in df.iteritems():
  #print(date)
  print(date.offsets.MonthOffset(4))
  print(date + pd.datetime(year = 0, month = 4, day = 0))

Upvotes: 0

Views: 412

Answers (1)

Shehan Ishanka
Shehan Ishanka

Reputation: 593

you can use below code to add 4 months.

from datetime import timedelta

for date in df[0]:
    print(date+timedelta(days=4*365/12))

or you can use this to change the dataframe by adding 4 months.

df.apply(lambda x:x+timedelta(days=4*365/12)

Refer this answer to add months directly.

Upvotes: 1

Related Questions