Python中将字符串日期转为纯date类型及datetime报错解决
Hey there! Let's work through your date conversion issue and fix that error first, then get you the clean pure-date format you need.
First, Let's Squash That AttributeError
The error AttributeError: type object 'datetime.datetime' has no attribute 'datetime' comes from conflicting imports: you’ve got both import datetime and from datetime import datetime in your code. This creates a naming clash—when you reference datetime now, it points directly to the datetime.datetime class, not the top-level module.
So when you tried datetime.datetime.strptime, you’re essentially trying to access datetime.datetime.datetime which doesn’t exist. To fix this, stick to one import style:
- If you keep
from datetime import datetime, usedatetime.strptime()directly - If you use
import datetime, usedatetime.datetime.strptime()
Solution 1: Use Pandas (Most Efficient for DataFrames)
Since you’re working with a pandas DataFrame, using pandas’ built-in functions is way faster than apply() for large datasets. Here’s how to convert your 3/27/2010 strings to pure date objects (no timestamp attached):
import pandas as pd # Parse the string date into datetime, then extract just the date part df_patients['date_of_diagnosis_new'] = pd.to_datetime(df_patients['date_of_diagnosis'], format='%m/%d/%Y').dt.date
This will give you a column where each value is a Python datetime.date object (e.g., 2010-03-27 with no time component).
If you want to keep a pandas datetime64 type but with the time forced to 00:00:00 (effectively removing the timestamp), use .dt.normalize() instead:
df_patients['date_of_diagnosis_new'] = pd.to_datetime(df_patients['date_of_diagnosis'], format='%m/%d/%Y').dt.normalize()
Solution 2: Fixing the apply() Approach
If you prefer using strptime, here’s the corrected code (using the from datetime import datetime import style):
from datetime import datetime # Convert string to datetime, then extract the pure date part df_patients['date'] = df_patients['date_of_diagnosis'].apply(lambda x: datetime.strptime(x, '%m/%d/%Y').date())
Adding .date() gives you the pure date object; omit it if you want a datetime object with time set to 00:00:00.
Quick Pro Tips
- Always specify the
formatparameter when parsing dates—it makes parsing faster and avoids unexpected errors. For your3/27/2010format, the correct format string is%m/%d/%Y. - Pandas native methods are far more efficient for large DataFrames compared to row-wise
apply()calls.
内容的提问来源于stack exchange,提问作者Anita

