sqlite 来自int64的pd.to_DateTime表示日期为1970

wpx232ag  于 2022-11-14  发布在  SQLite
关注(0)|答案(3)|浏览(216)

我正在从sqlite3中读取OHLC,并且我的索引类型为int64:

index   open   high    low  close   volume  trade_count       vwap ticker
30273  2022-09-23 10:11:00+00:00  22.48  22.63  22.40  22.41  12289.0         13.0  22.417248    BKR

当我打印df.index时,我得到:

...
        23127, 23128, 23129, 23130, 23131, 23132, 23133, 23134, 23135,
        23136],
       dtype='int64', length=2427)

然后,我将索引转换为日期时间:

df = pd.read_sql_query("SELECT * from ohlc_minutes", conn)
df.index = pd.to_datetime(df.index, unit='s')

这给了我:

...
           '1970-01-03 16:15:48', '1970-01-03 16:15:49',
           '1970-01-03 16:15:50', '1970-01-03 16:15:51',
           '1970-01-03 16:15:52', '1970-01-03 16:15:53',
           '1970-01-03 16:15:54', '1970-01-03 16:15:55',
           '1970-01-03 16:15:56', '1970-01-03 16:15:57'],
          dtype='datetime64[ns]', length=2629, freq=None)

这就把我的日期转换到1970年了。
我只想使用我的df索引中出现的所有信息将其转换为普通的日期时间,例如:

2022-09-23 10:11:00+00:00

更新
已尝试按照JKR的建议使用.loc

df.loc['index'] =  pd.to_datetime(df.loc['index'], unit='s')

这给出了错误:

Traceback (most recent call last):
  File "/home/dan/Documents/code/wolfhound/vectorbt.py", line 19, in <module>
    df.loc['index'] =  pd.to_datetime(df.loc['index'], unit='s')
  File "/home/dan/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 967, in __getitem__
    return self._getitem_axis(maybe_callable, axis=axis)
  File "/home/dan/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 1205, in _getitem_axis
    return self._get_label(key, axis=axis)
  File "/home/dan/.local/lib/python3.10/site-packages/pandas/core/indexing.py", line 1153, in _get_label
    return self.obj.xs(label, axis=axis)
  File "/home/dan/.local/lib/python3.10/site-packages/pandas/core/generic.py", line 3864, in xs
    loc = index.get_loc(key)
  File "/home/dan/.local/lib/python3.10/site-packages/pandas/core/indexes/range.py", line 389, in get_loc
    raise KeyError(key)
KeyError: 'index'
iugsix8n

iugsix8n1#

问题是index是列,所以首先将其转换为df.index,也省略unit='s'

#index column to df.index
df = df.set_index('index')
#convert to DatetimeIndex
df.index = pd.to_datetime(df.index)

或者:

#convert index column to datetimes
df['index'] = pd.to_datetime(df['index'])
#convert column index to df.index
df = df.set_index('index')
6ie5vjzr

6ie5vjzr2#

to_datetime每默认POSIX时间使用次数(参见docIf 'unix' (or POSIX) time; origin is set to 1970-01-01.)
您可以更改指定origin或提供offset(如果您有POSIX时间但没有年份(相对))
您的输入格式是什么?

s8vozzvw

s8vozzvw3#

这是因为int是自纪元以来的秒数。参见示例https://www.epochconverter.com/

相关问题