如何用Pandas筛选Excel日期?筛选DateTime列代码报错求助
Hey there! Let's break down the two issues you're facing and fix them one by one.
1. Fixing the dt.date Syntax Error
First up, the error in msft['Tested On']dt.date is just a tiny syntax mistake—you're missing a dot between the column reference and .dt. The correct syntax to access date components is:
msft['Tested On'].dt.date
This converts full datetime values to date-only objects (stripping off hours/minutes/seconds), which is essential for accurate date filtering.
2. Correctly Filtering for a Specific Date
Your initial code df = msft[msft.Tested On == '2018-01-11'] likely failed because your Tested On column stores full datetime values (even if the time part isn't visible in Excel). Comparing directly to a date string only matches rows where the datetime is exactly 2018-01-11 00:00:00—most rows with that date but any other time won't be included.
Here are three reliable ways to capture all rows from 2018-01-11:
Method 1: Compare date objects
Convert the datetime column to date objects and match against a date instance:
from datetime import date target_date = date(2018, 1, 11) df = msft[msft['Tested On'].dt.date == target_date]
Method 2: Floor datetime to day level
Use .dt.floor('D') to strip the time component from datetime values, then compare to a timestamp:
import pandas as pd target_timestamp = pd.Timestamp('2018-01-11') df = msft[msft['Tested On'].dt.floor('D') == target_timestamp]
Method 3: Filter by date range
This is often the most robust approach, as it captures all datetimes from midnight of the target date up to (but not including) midnight the next day:
start_date = '2018-01-11' end_date = '2018-01-12' df = msft[(msft['Tested On'] >= start_date) & (msft['Tested On'] < end_date)]
Quick Pre-Filter Check
Before filtering, confirm your column is actually stored as datetime type with:
print(msft['Tested On'].dtype)
It should show something like datetime64[ns]. If not, convert it first using msft['Tested On'] = pd.to_datetime(msft['Tested On']).
内容的提问来源于stack exchange,提问作者gomathi subramanian

