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

如何将含无效值的Pandas Series转换为Timestamp,无效值设为None

将日期字符串Series转为时间戳并处理无效值

方法一:自定义函数结合异常捕获

针对你的需求,可以给apply传入带异常处理的自定义函数,遇到无法解析的无效值时返回None:

import datetime
import pandas as pd

def convert_to_timestamp(date_str):
    try:
        # 按指定格式解析字符串并转为时间戳
        return datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S").timestamp()
    except (ValueError, TypeError):
        # 格式错误或非字符串值时返回None
        return None

# 应用函数到Series
series = series.apply(convert_to_timestamp)

方法二:使用Pandas原生方法(更高效)

如果数据集较大,推荐用Pandas内置方法,性能更优:

import pandas as pd

# 第一步:将字符串转为datetime类型,无效值转为NaT(Not a Time)
datetime_series = pd.to_datetime(series, format="%Y-%m-%d %H:%M:%S", errors="coerce")

# 第二步:将datetime转为时间戳,NaT对应转为None
series = datetime_series.apply(lambda x: x.timestamp() if pd.notna(x) else None)

若可以接受用NaN代替None,第二步可简化:

# 利用Pandas datetime的纳秒级存储,除以1e9转为秒数,NaT会自动变成NaN
series = datetime_series.view('int64') // 10**9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 04:32:32