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

如何在Python pandas DataFrame中添加创建日期与修改日期列

为Pandas DataFrame添加自动维护的创建/修改日期列

核心方案:自定义TrackedDataFrame类

通过继承pandas.DataFrame并重写关键方法,实现新增行自动填充创建时间、修改行内容自动更新修改时间的功能。

import pandas as pd
from datetime import datetime

class TrackedDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 初始化时自动添加日期列(如果不存在)
        if 'created_at' not in self.columns:
            self['created_at'] = datetime.now()
        if 'updated_at' not in self.columns:
            self['updated_at'] = datetime.now()

    def _update_updated_at(self, indices=None):
        current_time = datetime.now()
        if indices:
            self.loc[indices, 'updated_at'] = current_time
        else:
            self['updated_at'] = current_time

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        # 修改非日期列时更新修改时间
        if key not in ['created_at', 'updated_at']:
            indices = value.index if isinstance(value, pd.Series) else None
            self._update_updated_at(indices)

    def append(self, other, ignore_index=False, **kwargs):
        # 新增行时自动设置创建和修改时间
        if isinstance(other, (pd.Series, pd.DataFrame)):
            other['created_at'] = datetime.now()
            other['updated_at'] = datetime.now()
        result = super().append(other, ignore_index=ignore_index, **kwargs)
        return TrackedDataFrame(result)

# 测试用例
if __name__ == '__main__':
    # 初始化带数据的实例
    df = TrackedDataFrame({'col1': [1, 2], 'col2': ['x', 'y']})
    print("初始状态:\n", df)

    # 修改单行数据
    df.loc[0, 'col1'] = 99
    print("\n修改第一行后:\n", df)

    # 新增一行
    new_row = pd.Series({'col1': 3, 'col2': 'z'})
    df = df.append(new_row, ignore_index=True)
    print("\n新增行后:\n", df)

关键细节说明

  • 新增行时,created_at和updated_at会自动设为当前时间;
  • 修改任意非日期列的内容时,对应行的updated_at会自动更新;
  • 若需要UTC时间,将datetime.now()替换为datetime.utcnow()即可;
  • 批量修改整列时,会更新所有行的updated_at,如需精准控制修改行,可扩展索引判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:40:35