简体   繁体   中英

How can I convert the datetime intervals into a dataframe?

I would like to make a dataframe of dates with an interval of a week. I have used the following codes to generate a list of dates but when I want to make this into a dataframe, I got this error:

ValueError: DataFrame constructor not properly called!

Could you give me a hlep?

import pandas as pd

from datetime import date, datetime, timedelta

def perdelta(start, end, delta):
    curr = start
    while curr < end:
        yield curr
        curr += delta

for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame(dates)


print(OP_dates.head(3))

Don't need a loop here:

OP_dates = pd.DataFrame(perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)))

Using a loop:

OP_dates = pd.DataFrame()
for dates in perdelta(date(1997, 7, 19), date(2020, 5, 25), timedelta(days=7)):
    OP_dates = pd.DataFrame.append(OP_dates, [dates])

Are you familiar with pandas.date_range ? I believe this does exactly what you want:

import pandas as pd

date_range = pd.date_range('7-19-1997','5-25-2020',freq='1W')

#if you want the dates as entries
df = pd.DataFrame(date_range)

#or if you want the dates as the index:
df = pd.DataFrame(index=date_range)

Looks like someone just posted a fix using your perdelta function which also works - the issue was that your for loop tried to make a DataFrame for each date yielded from perdelta rather than making a single DataFrame for a collection/array of the dates yielded by perdelta .

JSYK you can also use datetimes with pandas.date_range , instead of the time strings I used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM