gpt4 book ai didi

python - pandas.tslib.Timestamp 日期匹配

转载 作者:太空宇宙 更新时间:2023-11-03 15:08:52 24 4
gpt4 key购买 nike

我正在尝试找到一种方法来检查 item_date 是否包含今天的日期。但即使我对其进行硬编码,打印 True 也永远不会发生。任何人都知道如何解决这个问题?

for item_date in buy_crossing_dates:
print item_date
print type(item_date)
if item_date == '2015-03-25 00:00:00':
print 'True'

结果:

2015-03-25 00:00:00
<class 'pandas.tslib.Timestamp'>

最佳答案

在 pandas 时间戳系列中检查今天日期的两个选项 ...

import pandas as pd

# option 1 - compare using python datetime.date objects
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31')) # Timestamps
python_dates = pd.Series([x.date() for x in dates]) # datetime.date
today = pd.Timestamp('now').date() # datetime.date
print(python_dates[python_dates == today])

# option 2 - compare pandas.Timestamp objects using Series.dt accessor
dates = pd.Series(pd.date_range('2015-01-01', '2016-12-31')) # Timestamps
today = pd.Timestamp('now') # Timestamp
print(dates[(dates.dt.year == today.year) &
(dates.dt.month == today.month) &
(dates.dt.day == today.day)])

注意:选项一使用列表理解将 pandas 时间戳系列转换为 datetime.date 对象系列(使用 pandas.Timestamp.date() 方法)。

关于python - pandas.tslib.Timestamp 日期匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29623309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com