如何使用列表 (datetime.timedelta) 中的特定日期循环并提取到不同的 csv 文件

How to use for loop specific days from list (datetime.timedelta) and extract to different csv files

以下代码不正确,因为 datetime.timedelta(day = " ") 必须包含整数而不是字符串。

参考 link

这种情况下很难定义新函数,有什么简单易行的方法解决吗?

--已解决--通过添加:day=int(day in string format)

def get_data():

    # Every stock can loop on every periods
    stocks = ['A', 'B', 'C', 'D', 'E','F','G','H']

    # since the limitation of API data provider, ~180 days' data can be extracted per request 
    periods = ['0','178','356','534']

    for x in stocks:

        for _ in range(10):
            tws.reqHistoricalData(x)

            for n in periods:

                data = pd.DataFrame(reqHistoricalData(datetime.datetime.today()- datetime.timedelta(days=n)).strftime("%Y%m%d %H:%M:%S %Z"))

                # if there are any empty data, it can "smart" loop back and start from corresponding stock AND period without running again from the beginning
                if not data.empty:
                    #1 st Edited
                    data.to_csv("filename"+x+"@"+n+".csv")
                    break

                print("Data is empty")

现有代码仅导出文件名A@0、文件名B@0、文件名C@0..... 但是不能像下面这样导出到不同的csv文件

data.to_csv("filename"+x+"@"+n+".csv")

filenameA@0.csv
filenameA@178.csv 
filenameA@356.csv
filenameA@534.csv
filenameB@0.csv
filenameB@178.csv
filenameB@356.csv
filenameB@534.csv
filenameC@0.csv
..........

多谢指正,以下是解决方法

def get_data():

    # Every stock can loop on every periods
    stocks = ['A', 'B', 'C', 'D', 'E','F','G','H']    

    periods = [0,178,356,534,712]

    for x in stocks:

        for n in periods:
            tws.reqHistoricalData(x)

            for _ in range(10): # repeat it only 10 times
                today = datetime.datetime.today()
                delta = datetime.timedelta(days=n)
                data = pd.DataFrame(reqHistoricalData(today-delta).strftime("%Y%m%d %H:%M:%S %Z"))

                if not data.empty:
                    data.to_csv("filename{}@{}.csv".format(x, n))
                    break # exit `for _` loop so it doesn't read again for the same period

                print("empty data for", x, str(n), '... reading again')
                tws.reqHistoricalData(x) # read again for the same period