如何将接口获取的DateTime时间戳作为列追加到Python DataFrame
解决方法
你原本的代码存在3个问题:
- 接口返回的时间戳变量命名为
time,覆盖了导入的time模块,会导致后续调用time.time()报错 - 你在方法内已经拿到了网页端的时间,但没有把这个值传递到外部的DataFrame处理逻辑里
- 最后一行的
Print首字母大写不符合Python语法,运行会报错
修改后的完整可运行代码如下:
import requests import pandas as pd import time from datetime import datetime class NseIndia2: def __init__(self): self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'} self.session = requests.Session() self.session.get("http://nseindia.com", headers=self.headers) def get_option_chain(self, symbol, indices=False): if not indices: url = 'https://www.nseindia.com/api/option-chain-equities?symbol=' + symbol else: url = 'https://www.nseindia.com/api/option-chain-indices?symbol=' + symbol # 修改变量名避免覆盖time模块,拿到网页返回的时间字符串 web_timestamp_str = self.session.get(url,headers=self.headers).json()["records"]['timestamp'] # 把字符串转成datetime格式,方便后续时间维度的分析计算 web_datetime = datetime.strptime(web_timestamp_str,'%d-%b-%Y %H:%M:%S') data = self.session.get(url,headers=self.headers).json()["records"]["data"] my_df = [] for i in data: for k, v in i.items(): if k == "CE" or k == "PE": info = v info["instrumentType"] = k my_df.append(info) df = pd.DataFrame(my_df) # 直接给所有行追加时间列,效果和你Power BI里向下填充完全一致 df["recordedat"] = web_datetime return df nse = NseIndia2() df = nse.get_option_chain("NIFTY",indices=True) print(df["recordedat"]) print(df)
如果不需要datetime类型,只想存和接口返回一致的字符串格式,把赋值给recordedat列的web_datetime替换为web_timestamp_str即可。
内容的提问来源于stack exchange,提问作者Utkarsh Pandya
相关产品推荐
相关产品推荐

