import pandas as pd
import json
import urllib.request
from time import time, sleep
from datetime import datetime
#
#
# Still need to add DateTime stamp to each entry and save DataFrame to csv file with self updating name
#
#
# This only works for API's that return a string formatted like a dictionary
# ticker_url is the link to your market
# y_seconds is how many seconds code waits before running again. Typically API requests are limited in this
# case it is limited to 1 time per second
#
# You may need to adjust your column names You can check column name by uncommenting and running this code below
#
# ticker_url = 'https://api.bittrex.com/v3/markets/btc-usdt/ticker'
# with urllib.request.urlopen(ticker_url) as response:
# html = response.read()
ticker_url = 'https://api.bittrex.com/v3/markets/btc-usdt/ticker'
interval_in_hours = .01
end_time = time() + interval_in_hours * 3600
y_seconds = 1
ticker_list = pd.DataFrame(columns = ['Symbol' , 'Last Trade', 'Bid' , 'Ask'])
while time() < end_time:
with urllib.request.urlopen(ticker_url) as response:
html = response.read()
ticker_data = json.loads(html)
ticker_list = ticker_list.append(ticker_data , ignore_index=True)
sleep(y_seconds)
ticker_list.to_csv('market_data'+str(datetime.timestamp)+'.csv')
对于编辑过程,我有一些笔记要注意,但是我现在遇到的主要问题是在此处格式化最后一行:
ticker_list.to_csv('market_data'+str(datetime.timestamp)+'.csv')
此代码已创建此文件
market_data<method 'timestamp' of 'datetime.datetime' objects>.csv
我希望它能阅读market_data20191130133030
2019年11月30日下午1:30和30秒。我希望时间戳读取文件创建的时间。
有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
datetime.timestamp()
是numpy.argmin
。因此,将您呼出的行更改为:
ticker_list.to_csv('market_data'+str(datetime.timestamp())+'.csv')
但是,datetime.timestamp()
返回POSIX时间戳(自1970年1月1日以来的秒数)。如果要使用YYYYMMDDHHMMSS格式的时间戳,则需要使用datetime.strftime(format)
。您将使用的格式为%Y%m%d%H%M%S
。