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

如何使用Pandas便捷转换TZ格式时间字符串为日期?

问题:将ISO格式时间列转换为仅日期格式

原始DataFrame:

creationDate
0       2022-06-02T12:41:47.498Z
1       2022-06-02T12:45:13.994Z
2       2022-06-02T12:58:57.684Z
3       2022-06-02T13:24:59.379Z
4       2022-06-02T13:29:57.304Z

期望转换后的格式:

creationDate
0       2022-06-02
1       2022-06-02
2       2022-06-02
3       2022-06-02
4       2022-06-02

你已有的两种有效方法:

  • 方法一:日期时间解析后格式化
df["creationDate"] = pd.to_datetime(df["creationDate"]).dt.strftime("%Y-%m-%d")
  • 方法二:逐行字符串切片
df["creationDate"] = df["creationDate"].apply(lambda x: x[:10])

更优的实现方式

以下几种方法在效率或简洁性上更具优势:

  1. 矢量化字符串切片(比apply高效,属于pandas内置矢量化操作,避免逐行循环):
df["creationDate"] = df["creationDate"].str[:10]
  1. 直接提取日期对象(若不需要字符串格式,保留datetime.date类型更高效,还能复用日期相关操作):
df["creationDate"] = pd.to_datetime(df["creationDate"]).dt.date

如果需要转为字符串格式,可追加类型转换:

df["creationDate"] = pd.to_datetime(df["creationDate"]).dt.date.astype(str)
  1. 指定解析格式加速转换(若时间格式固定为YYYY-MM-DDTHH:MM:SS.sssZ,指定format参数能大幅提升解析速度):
df["creationDate"] = pd.to_datetime(df["creationDate"], format="%Y-%m-%dT%H:%M:%S.%fZ").dt.strftime("%Y-%m-%d")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 16:55:17