我在将 Excel 文件中的日期列读取到 Pandas DataFrame 中时遇到问题。我的 Excel 工作表中的日期值格式为 DD-MM-YYYY(例如 05-03-2024),但是当我使用 pd.read_excel 时,Pandas 将这些值解释为日期时间对象并附加 00:00:00,从而导致输出如下:
Actual Delivery Date
0 2024-03-05 00:00:00
1 2024-03-05 00:00:00
2 2024-03-05 00:00:00
3 2024-03-05 00:00:00
我尝试过以下方法但没有成功:
读取Excel文件时使用dtype=str。 加载后将日期列显式转换为字符串。
import pandas as pd
def load_excel_sheet(file_path, sheet_name):
excel_file = pd.ExcelFile(file_path, engine='openpyxl')
df_pandas = pd.read_excel(excel_file, sheet_name=sheet_name, dtype=str)
# Explicitly convert specific date columns to strings
for col in df_pandas.columns:
if df_pandas[col].dtype == 'datetime64[ns]':
df_pandas[col] = df_pandas[col].astype(str)
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())
尽管做出了这些努力,我的日期列仍然出现在 DataFrame 中,并附加了 00:00:00。如何确保 Pandas 严格将这些日期值读取为字符串,而不需要任何额外的时间信息?
您可以使用
.dt
访问器格式化不带时间的日期时间对象:
from datetime import date
for col in df_pandas.columns:
if df_pandas[col].dtype == 'datetime64[ns]':
df_pandas[col] = df[col].dt.date.astype(str)