pandas pandas中datetime和datetime64[ns]的比较

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51827134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:56:15  来源:igfitidea点击:

Comparison between datetime and datetime64[ns] in pandas

pythonpandasdatetimedatetime64

提问by JesusMonroe

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

我正在编写一个检查 excel 文件的程序,如果今天的日期在 excel 文件的日期列中,我会解析它

I'm using:

我正在使用:

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

I do know for a fact that today's date is in the file in question. The dtype of the series is datetime64[ns]

我确实知道今天的日期在相关文件中。该系列的 dtype 是 datetime64[ns]

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:

另外,如果这很重要,我只检查日期本身而不是之后的时间戳。我这样做是为了使时间戳为 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

打印后该对象的类型也是日期时间

回答by piRSquared

You can use

您可以使用

pd.Timestamp('today')

or

或者

pd.to_datetime('today')

But both of those give the date and time for 'now'.

但是这两个都给出了 的日期和时间'now'



Try this instead:

试试这个:

pd.Timestamp('today').floor('D')

or

或者

pd.to_datetime('today').floor('D')


You could have also passed the datetimeobject to pandas.to_datetimebut I like the other option mroe.

您也可以将datetime对象传递给,pandas.to_datetime但我喜欢另一个选项 mroe。

pd.to_datetime(datetime.datetime.today()).floor('D')


Pandas also has a Timedeltaobject

Pandas也有Timedelta对象

pd.Timestamp('now').floor('D') + pd.Timedelta(-3, unit='D')

Or you can use the offsetsmodule

或者你可以使用offsets模块

pd.Timestamp('now').floor('D') + pd.offsets.Day(-3)


To check for membership, try one of these

要检查会员资格,请尝试其中之一

cur_date in df['date'].tolist()

Or

或者

df['date'].eq(cur_date).any()