【问题标题】:comparing datetime index pandas array to datetime object将日期时间索引熊猫数组与日期时间对象进行比较
【发布时间】:2021-11-05 08:15:42
【问题描述】:

我正在尝试在某个时间戳之前删除 pandas 数据帧中的任何数据(我现在在此示例中使用)

candle_data[min] 是我的数据框...

candle_data[min].loc[candle_data[min].index < pd.to_datetime(datetime.datetime.utcnow(), unit='ns')]
TypeError: Invalid comparison between dtype=datetime64[ns, UTC] and Timestamp

这里是数据数据框

candle_data[min].loc[candle_data[min].index]
                           volume  complete        o        h        l        c
time                                                                           
2021-09-06 20:00:00+00:00     353      True  1.25344  1.25374  1.25324  1.25362
2021-09-06 20:05:00+00:00     125      True  1.25357  1.25357  1.25320  1.25338
2021-09-06 20:10:00+00:00      75      True  1.25336  1.25354  1.25332  1.25333
2021-09-06 20:15:00+00:00      70      True  1.25336  1.25356  1.25331  1.25336
2021-09-06 20:20:00+00:00      68      True  1.25333  1.25352  1.25332  1.25338
...                           ...       ...      ...      ...      ...      ...
2021-09-08 13:45:00+00:00     429      True  1.26782  1.26891  1.26758  1.26879
2021-09-08 13:50:00+00:00     363      True  1.26877  1.26901  1.26822  1.26831
2021-09-08 13:55:00+00:00     340      True  1.26829  1.26832  1.26657  1.26680
2021-09-08 14:00:00+00:00    1219      True  1.26688  1.26797  1.26460  1.26790
2021-09-08 14:05:00+00:00     654      True  1.26786  1.26858  1.26641  1.26650
[499 rows x 6 columns]

这就是 pd.to_datetime 给我的

pd.to_datetime(datetime.datetime.utcnow(), unit='ns')
Timestamp('2021-09-08 14:34:37.175469')

我尝试查看其他文章和谷歌,但未能避免与此非常相似的消息...如何将时间戳转换为可以比较的东西?

【问题讨论】:

  • 为什么要首先使用 Python 日期时间?您可以只使用 pandas 类型,例如pd.Timestamp('2021-09-08 14:34:37.175469')pd.Timestamp('now')

标签: python pandas dataframe datetime


【解决方案1】:

无论您使用pd.Timestamp 对象(通过在您的问题中使用pd.to_datetime 方法创建)还是直接使用Python datetime 库都可以。在某些情况下存在一些差异(在使用 DataFrames 时,我通常更愿意坚持使用 pandas 对象),但在您的情况下,问题在于时区差异。

您的索引已本地化 (datetime64[ns, UTC]),但不是您的 datetime 对象。由于您使用utcnow 方法,因此可能会让某些人感到有些困惑。此方法将返回 utc 当前时间,但未本地化意味着它是一个没有时区的日期时间对象

解决方案很简单,您可以执行以下操作之一(您可以尝试一下以了解其工作原理):

  • 使用不带时区的索引:candle_data.index.tz_localize(None) &lt; pd.to_datetime(datetime.datetime.utcnow(), unit='ns')
  • 本地化您的时间戳对象:candle_data.index &lt; pd.to_datetime(datetime.datetime.utcnow(), unit='ns', utc=True)
  • 在不使用日期时间的情况下本地化您的 Timestamp 对象:candle_data[min].index &lt; pd.Timestamp("now", tz="UTC")

而且有越来越多的方法可以做到这一点。我通常会建议使用切片而不是这样的比较索引。你可以做例如以下:

candle_data[:datetime.datetime.utcnow()]
# or
candle_data[:pd.Timestamp("now")]

它将返回索引日期时间小于当前时间的所有数据。

【讨论】:

    猜你喜欢
    • 2020-10-02
    • 2014-02-12
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2017-07-02
    • 1970-01-01
    相关资源
    最近更新 更多