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

时间:2018-08-04 00:50:23

标签: python for-loop break python-datetime

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

从链接How to use for loop and add one day (timedelta) every time中获取参考

在这种情况下很难定义新功能,有没有简便的解决方法?

-已解决-通过添加:day = int(日期以字符串格式)

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")

现有代码仅导出具有filenameA @ 0,filenameB @ 0,filenameC @ 0 .....的cvs 但是,不能将其导出为以下不同的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
..........

1 个答案:

答案 0 :(得分:0)

感谢您提供剩余的呋喃盐,以下是解决方法

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