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

如何为Polars DataFrame添加含当前日期时间值的列?

为Polars DataFrame添加当前日期时间列的方法

有几种简单的方式可以实现这个需求:

方法1:用Python标准库datetime配合Polars的lit函数

通过pl.lit()将当前日期时间转为常量值,再添加为新列:

import polars as pl
from datetime import datetime

# 示例DataFrame
df = pl.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]})

# 添加当前日期时间列
df = df.with_columns(pl.lit(datetime.today()).alias("date"))

方法2:直接使用Polars内置的datetime.now()函数

Polars自带日期时间工具,无需额外导入datetime模块:

import polars as pl

df = pl.DataFrame({"col1": [1, 2, 3], "col2": ["a", "b", "c"]})

# 添加当前日期时间列
df = df.with_columns(pl.datetime.now().alias("date"))

和Pandas写法的对比

你提到的Pandas实现方式:

import pandas as pd
df["date"] = pd.Timestamp.today()

需要注意:Polars的with_columns方法会返回新的DataFrame(默认不修改原数据),所以需要重新赋值;而Pandas的写法是直接在原DataFrame上修改列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:17:38