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

Python/Pandas字符串时间戳增加指定毫秒数的实现方法

给字符串格式的纳秒级时间戳增加指定毫秒数

你的时间戳1675242910384942479是纳秒级(19位数字,1秒 = 109纳秒),100毫秒等于108纳秒(100ms = 100 * 10^6 ns)。下面是两种场景的实现方案:

基础Python函数实现

直接将字符串时间戳转为整数,加上对应纳秒数后转回字符串即可:

def add_n_ms_to_timestamp(n_ms: int, timestamp_str: str) -> str:
    timestamp_ns = int(timestamp_str)
    delta_ns = n_ms * 10**6  # 毫秒转纳秒
    new_timestamp_ns = timestamp_ns + delta_ns
    return str(new_timestamp_ns)

测试示例:

original_ts = "1675242910384942479"
updated_ts = add_n_ms_to_timestamp(100, original_ts)
print(updated_ts)  # 输出: 1675242910484942479

Pandas批量处理场景

如果需要处理DataFrame中的时间戳列,用矢量化操作更高效:

import pandas as pd

# 示例数据
df = pd.DataFrame({
    "timestamp": ["1675242910384942479", "1675242911384942479", "1675242912384942479"]
})

def add_n_ms_batch(n_ms: int, ts_series: pd.Series) -> pd.Series:
    delta_ns = n_ms * 10**6
    return (ts_series.astype(int) + delta_ns).astype(str)

# 生成新列
df["updated_timestamp"] = add_n_ms_batch(100, df["timestamp"])
print(df)

注意点

  • 若你的时间戳是毫秒级(13位数字),直接去掉*10**6,直接加n_ms即可
  • 可以根据需求添加异常处理,比如捕获非整数格式的时间戳输入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:50:22