You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中将字符串日期转为纯date类型及datetime报错解决

Fixing Date Conversion to Pure Date Type in Python/Pandas

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, use datetime.strptime() directly
  • If you use import datetime, use datetime.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 format parameter when parsing dates—it makes parsing faster and avoids unexpected errors. For your 3/27/2010 format, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:55:14