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

如何让Pandas读取Excel日期列时仅保留字符串格式不含时间部分

解决Pandas读取Excel日期列时保留DD-MM-YYYY格式字符串的问题

问题根源

你之前尝试的dtype=str参数之所以无效,是因为Excel中的日期本质是数值类型,openpyxl引擎会先将其解析为datetime对象,再转换为字符串,因此会带上00:00:00后缀。同时,此时列的类型为object(存储字符串),而非datetime64[ns],导致你后续判断列类型的循环代码根本不会执行,自然无法完成格式修正。

可行解决方案

方案一:读取时直接指定列转换规则(推荐)

使用pd.read_excel的converters参数,针对日期列自定义转换函数,将datetime对象直接格式化为DD-MM-YYYY的字符串:

import pandas as pd

def load_excel_sheet(file_path, sheet_name):
    excel_file = pd.ExcelFile(file_path, engine='openpyxl')
    # 指定日期列的转换函数,空值保持原状态
    converters_dict = {
        'Actual Delivery Date': lambda x: x.strftime('%d-%m-%Y') if pd.notnull(x) else x
    }
    df_pandas = pd.read_excel(excel_file, sheet_name=sheet_name, converters=converters_dict)
    return df_pandas

def process_data_quality_checks(file_path, sheet_name):
    df = load_excel_sheet(file_path, sheet_name)
    
    for col in df.columns:
        if not all(isinstance(x, str) for x in df[col]):
            print(f"Column {col} has non-string data")
        else:
            print(f"Column {col} is all strings")
    
    return df

file_path = r"path_to_your_excel_file.xlsx"
sheet_name = 'Sheet1'

df = process_data_quality_checks(file_path, sheet_name)
print(df.head())

方案二:读取后统一格式化日期列

如果不确定日期列名称,可先将数据读取为datetime类型,再遍历所有列将datetime类型列格式化为目标字符串:

import pandas as pd

def load_excel_sheet(file_path, sheet_name):
    excel_file = pd.ExcelFile(file_path, engine='openpyxl')
    # 不指定dtype,让Pandas自动解析日期为datetime类型
    df_pandas = pd.read_excel(excel_file, sheet_name=sheet_name)
    
    # 遍历所有列,识别datetime类型并格式化
    for col in df_pandas.columns:
        if pd.api.types.is_datetime64_any_dtype(df_pandas[col]):
            df_pandas[col] = df_pandas[col].dt.strftime('%d-%m-%Y')
    
    return df_pandas

# 后续process_data_quality_checks函数保持不变

效果验证

执行修改后的代码,日期列将以DD-MM-YYYY格式的字符串展示,例如:

Actual Delivery Date
0            05-03-2024
1            05-03-2024
2            05-03-2024
3            05-03-2024

内容的提问来源于stack exchange,提问作者Ash3060

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 19:52:36