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

Python新手求助:从Excel提取日期时间戳并添加至其他DataFrame

问题描述

我是Python新手,首次进行技术提问。尝试用Python从Excel表格单元格提取日期时间戳,编写了如下代码:

df = pd.read_excel(fileName, sheet_name=0)
df_columns = dict(zip(df.columns,range(len(df.columns))))
df_start = df.rename(columns=df_columns)
for i in range(0, len(df.columns)):
    for j in range(0, 4):
        if isinstance(df.iloc[i,j],str) and ':' in df.loc[i,j]:
            datestamp = datetime.datetime.strptime(df.iloc[i,j], '%d/%m/%Y %H:%M:%S')
            break

运行时出现报错信息“Error at 0”。

当前Excel导入后的DataFrame结构如下:
| 0 | 1 | 2 |...| 10 | 11 | 12 |
|---- | ----| --- |...|---- | ------------------------| --- |
| NaN | NaN | NaN |...| NaN | 2022-09-16 16:47:21.852 | NaN |
| NaN | NaN | NaN |...| NaN | 2022-09-16 16:47:21.852 | NaN |
| NaN | NaN | NaN |...| NaN | NaN | NaN |
| NaN | NaN | NaN |...| NaN | NaN | NaN |
| NaN |ClientName |Client Number |...|Core | Core Description | Status |
| NaN |AB09403880 |9403880|...|NaN | NaN | Active |
| NaN |AB09403881 |9403881|...|NaN | NaN | Active |
| NaN |AB09403882 |9403883|...|NaN | NaN | Active |

补充需求:需提取该日期时间戳作为新列添加至另一DataFrame,最终导出为CSV。日期时间戳所在列位置不固定,现有代码报错,寻求解决方法。

预期输出:
| Datestamp|ClientName |Client Number |...|Core | Core Description | Status |
| 2022-09-16 |AB09403880 |9403880|...|NaN | NaN | Active |
| 2022-09-16 |AB09403881 |9403881|...|NaN | NaN | Active |
| 2022-09-16 |AB09403882 |9403883|...|NaN | NaN | Active |


解决方法

1. 定位日期时间戳

原代码存在两个核心问题:循环遍历方向错误(列行颠倒)、日期格式不匹配(实际格式为YYYY-MM-DD HH:MM:SS.sss,却用%d/%m/%Y %H:%M:%S解析)。以下代码可快速定位目标日期:

import pandas as pd
from datetime import datetime

df = pd.read_excel(fileName, sheet_name=0)

target_date = None
# 遍历所有列,检查前5个非空值找日期
for col in df.columns:
    for val in df[col].dropna().head(5):
        try:
            # 解析带毫秒的日期时间,提取日期部分
            dt_obj = pd.to_datetime(val, format='%Y-%m-%d %H:%M:%S.%f')
            target_date = dt_obj.date()
            break
        except (ValueError, TypeError):
            continue
    if target_date is not None:
        break

2. 提取有效业务数据并添加日期列

先定位表头行(含ClientName的行),再加载下方的客户数据,最后插入日期列:

# 找到表头所在行的索引
header_idx = df[df.apply(lambda row: 'ClientName' in row.values, axis=1)].index[0]
# 从表头下一行加载数据,重置索引
client_data = df.loc[header_idx + 1:].reset_index(drop=True)
# 设置正确的列名
client_data.columns = df.loc[header_idx].values
# 在第一列插入日期
client_data.insert(0, 'Datestamp', target_date)
# 清理全空的无效行
client_data = client_data.dropna(how='all')

3. 导出为CSV文件

client_data.to_csv('client_output.csv', index=False)

关键优化点

  • 使用pd.to_datetime替代手动strptime,自动兼容带毫秒的日期格式,容错性更强
  • 通过表头行定位有效数据,避免因Excel格式混乱导致的数据错位
  • 日期列插入到首列,完全匹配预期输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:30:51