Pandas datetime strange behaviour by time selection with string

Viewed 38

I have the following datetime series:

0   2021-05-19 00:00:00
1   2021-05-19 00:00:00
2   2021-05-19 00:00:00
3   2021-05-19 00:00:00
4   2021-05-19 00:00:00
5   2021-05-19 23:59:00
6   2021-05-19 23:59:00
7   2021-05-19 23:59:00
8   2021-05-19 23:59:00
9   2021-05-19 23:59:00
Name: Ab, dtype: datetime64[ns]

If I use this selection method:

s[s.dt.date == datetime.date(2021, 5, 19)]

I get all data:

0   2021-05-19 00:00:00
1   2021-05-19 00:00:00
2   2021-05-19 00:00:00
3   2021-05-19 00:00:00
4   2021-05-19 00:00:00
5   2021-05-19 23:59:00
6   2021-05-19 23:59:00
7   2021-05-19 23:59:00
8   2021-05-19 23:59:00
9   2021-05-19 23:59:00
Name: Ab, dtype: datetime64[ns]

But if I use this short one:

s[s == '2021-05-19']

I get only midnight samples:

0   2021-05-19
1   2021-05-19
2   2021-05-19
3   2021-05-19
4   2021-05-19
Name: Ab, dtype: datetime64[ns]

What are the best practices to deal with such cases? Thank you!

1 Answers

If compare by dates output is expected because only dates are compared by scalar date.

If compare by string then Pandas compares like datetime with 00:00:00 times, so the output is 2021-05-19 00:00:00, but because all dates have the same 00:00:00 times they are not displayed.

Related