【发布时间】:2023-03-30 22:25:02
【问题描述】:
我正在尝试将列纳秒转换为日期格式。我想,正如我之前读到的那样,来自 Binance 的时间戳以毫秒为单位,但它似乎以 ns 为单位,如果它对其他人有帮助的话:
0 1.595948e+12
1 1.595952e+12
2 1.595956e+12
3 1.595959e+12
4 1.595963e+12
495 1.597730e+12
496 1.597734e+12
497 1.597738e+12
498 1.597741e+12
499 1.597745e+12
Name: time, Length: 500, dtype: float64
所以我需要乘以超过 1.000.000 才能获得正确的日期,应用“pd.to_datetime(df['time'])” 我这样做了,我打印了 dataFrame,我得到了它,但是代码停止并出现两个不同的错误取决于我如何执行 mult:
选择 A '''
将值从字符串转换为浮点数和毫秒到日期
for col in col_names:
df[col] = df[col].astype(float)
df['time'] = df['time'].apply(lambda x: x*1000000)#<<this one
df['time'] = pd.to_datetime(df['time'])
#print (df['time'])
''' 我收到此错误:
df['time'] = df['time'].apply(lambda x: x*1000000)
TypeError: unsupported operand type(s) for /: 'Timestamp' and 'int'
选项 B
'''
将值从字符串转换为浮点数和毫秒到日期
for col in col_names:
df[col] = df[col].astype(float)
df['time'] = df['time']*1000000 #<<<<<<<<<<<this one
df['time'] = pd.to_datetime(df['time'])
#print (df['time'])
'''
但它引发了以下错误:
raise TypeError(f"cannot perform {name} with this index type: {typ}") TypeError: cannot perform mul with this index type: DatetimeArray
在这两种情况下,rpint(df) 似乎都是正确的:
495 2020-08-17 15:00:00
496 2020-08-17 16:00:00
497 2020-08-17 17:00:00
498 2020-08-17 18:00:00
499 2020-08-17 19:00:00
Name: time, Length: 500, dtype: datetime64[ns]
Traceback (most recent call last):
我将不胜感激。
下面的整个代码,我用“#this”标记了这两行,如果注释代码运行正常,但日期在 70 年,但未注释或者它们会引发正确的日期,但代码会在错误中停止(抱歉,如果这不是暴露周围事物的正确方式):
'''
import pandas as pd
import requests
import json
class TradingModel:
def __init__(self, symbol):
self.symbol = symbol
self.df = self.getData()
def getData(self):
# define URL
base = 'https://api.binance.com'
endpoint = '/api/v1/klines'
params = '?&symbol='+self.symbol+'&interval=1h'
url = base + endpoint + params
# download data
data = requests.get(url)
dictionary = json.loads(data.text)
# put in dataframe and clean-up
df = pd.DataFrame.from_dict(dictionary)
df = df.drop(range(6, 12), axis=1)
# rename columns
col_names = ['time', 'open', 'high', 'low', 'close', 'volume']
df.columns = col_names
# transform values from strings to floats and millis to date
for col in col_names:
df[col] = df[col].astype(float)
#df['time'] = df['time'].apply(lambda x: x*1000000) #this
df['time'] = df['time']*1000000 #this
df['time'] = pd.to_datetime(df['time'])
print (df['time'])
def Main():
symbol = "LINKUSDT"
model = TradingModel(symbol)
model.getData()
if __name__ == '__main__':
Main()
'''
【问题讨论】:
-
感谢您的更新。但是,我的回答仍然有效:您声称打印日期列时它看起来正确。如果是这样,那么我看不出你哪里有问题。请提供预期的minimal, reproducible example。显示中间结果与您的预期不同的地方。到目前为止,您声称中间结果是您所期望的。
-
嗨 prune,上传代码没有问题。我正在编辑整个代码的问题。谢谢
-
请发布一份 MRE;发布您的整个代码库是不合适的。
-
用 MRE 编辑,感谢新手提示。