pandashelp
pandashelp

Reputation: 13

How to iterate over dates in a dataframe?

I've got a dataframe that has a column of dates that are formatted like this:

"1/1/2016"

I would like to create a for-loop that starts from that date and goes to "1/2/2016", "1/3/2016", and so on.

I start with this Python code:

df = pd.read_csv('myfile.csv')
df['dates'] = pd.to_datetime(df['dates'])

Which turns the date format to this: '01-01-2016' Next:

start_date = '01-01-2016'

Finally, the for-loop:

for j in range (1,30)
    start_date + j...

But you can't add an integer to that date format, of course. What should I do in the for-loop to just go to the next day?

Upvotes: 1

Views: 8724

Answers (4)

Dodge
Dodge

Reputation: 3309

You can add a day with timedelta()

Import datetime

for j in range (1,30):
    start_date + datetime.timedelta(days=1)

Here is a LINK to the docs for your reference

Upvotes: 0

Miruska Malyschka
Miruska Malyschka

Reputation: 43

To increase the date by one day if your are pandas' lover:

df['dates'].iloc[0] +pd.to_timedelta(1,'d')

Or you can try this :

from datetime import timedelta
df['dates'].iloc[0] + timedelta(days=1)  #on the left side is the date you want to increase

You can find more infos here https://stackoverflow.com/a/6871054/8433650

Upvotes: 1

Naga kiran
Naga kiran

Reputation: 4607

By using numpy time delta either you can add day or subtract from time stamp

import numpy as np
import pandas as pd
pd.to_datetime('01-01-2016') +np.timedelta64(1,'D')

Upvotes: 0

sacuL
sacuL

Reputation: 51335

I'm not sure what your final outcome wants to be, but you can use pd.date_range:

start_date = pd.to_datetime('01-01-2016')

for j in pd.date_range(start_date, periods=30):
    print(j)

Which gives you:

2016-01-01 00:00:00
2016-01-02 00:00:00
2016-01-03 00:00:00
2016-01-04 00:00:00
2016-01-05 00:00:00
2016-01-06 00:00:00
...

Upvotes: 2

Related Questions