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

如何在apply结合datetime函数时配置日在前的日期格式?

解决方法:给apply中的pd.to_datetime传递dayfirst参数

嘿,这个问题我之前处理多列日期格式化时也碰到过!其实只需要把dayfirst=True这个参数传递给apply里的pd.to_datetime就行,这里有两种简单好用的方法:

方法1:用lambda函数直接传递参数

这是最直观的方式,通过lambda接收每一列数据,然后调用pd.to_datetime时带上dayfirst=True:

df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]] = df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]].apply(lambda col: pd.to_datetime(col, dayfirst=True))

这样每一列都会按照**日在前(d/m/yyyy)**的格式去解析日期,和你之前处理单列的逻辑完全一致。

方法2:用functools.partial绑定参数(适合复用场景)

如果之后还要多次用到这个带dayfirst=True的日期解析逻辑,可以用partial把参数提前绑定好,代码更简洁:

from functools import partial

# 先创建一个绑定了dayfirst=True的日期解析函数
parse_dayfirst_date = partial(pd.to_datetime, dayfirst=True)
# 再用apply批量处理列
df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]] = df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]].apply(parse_dayfirst_date)

额外小技巧:处理解析错误

如果某些列里存在无法解析的非日期值,怕报错中断处理的话,可以加上errors='coerce'参数,把无效值转为NaT(pandas的空日期类型):

df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]] = df2[["Detection_time", "Device_ack", "Reset/Run", "Duration"]].apply(lambda col: pd.to_datetime(col, dayfirst=True, errors='coerce'))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:35:50