pandas 的datetime和datetime64 [ns]之间的比较 [英] Comparison between datetime and datetime64[ns] in pandas
问题描述
我正在编写一个检查excel文件的程序,如果今天的日期在excel文件的日期列中,我将对其进行解析
I'm writing a program that checks an excel file and if today's date is in the excel file's date column, I parse it
我正在使用:
cur_date = datetime.today()
今天的日期.我正在检查今天是否在以下列中:
for today's date. I'm checking if today is in the column with:
bool_val = cur_date in df['date'] #evaluates to false
我确实知道今天的日期在有问题的文件中.系列的dtype是datetime64 [ns]
I do know for a fact that today's date is in the file in question. The dtype of the series is datetime64[ns]
此外,我只检查日期本身,而不检查事后的时间戳,如果这很重要的话.我这样做是为了将时间戳记为00:00:00:
Also, I am only checking the date itself and not the timestamp afterwards, if that matters. I'm doing this to make the timestamp 00:00:00:
cur_date = datetime.strptime(cur_date.strftime('%Y_%m_%d'), '%Y_%m_%d')
打印后该对象的类型也是日期时间
And the type of that object after printing is datetime as well
推荐答案
您可以使用
pd.Timestamp('today')
或
pd.to_datetime('today')
但是,两者都给出了'now'
的日期和时间.
But both of those give the date and time for 'now'
.
尝试以下方法:
pd.Timestamp('today').floor('D')
或
pd.to_datetime('today').floor('D')
您也可以将 datetime
对象传递给 pandas.to_datetime
,但是我喜欢其他选项mroe.
You could have also passed the datetime
object to pandas.to_datetime
but I like the other option mroe.
pd.to_datetime(datetime.datetime.today()).floor('D')
熊猫还有一个 Timedelta
对象
pd.Timestamp('now').floor('D') + pd.Timedelta(-3, unit='D')
或者您可以使用 offsets
模块
pd.Timestamp('now').floor('D') + pd.offsets.Day(-3)
要检查成员身份,请尝试以下一种方法
To check for membership, try one of these
cur_date in df['date'].tolist()
或
df['date'].eq(cur_date).any()
这篇关于 pandas 的datetime和datetime64 [ns]之间的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!