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

Python中pd.to_datetime转换Unix时间戳为日期返回错误结果的问题

Fixing Incorrect 1970 Date Conversion from Unix Timestamps in Pandas

Got it, let's break down why your pandas code is spitting out those wrong 1970 dates, and how to fix it to match the correct result you got with datetime.

The Root Cause

Your pandas code has two key issues that are throwing off the conversion:

  • Unnecessary format parameter: The format argument is meant for parsing string dates (like "2019-01-02"), not numeric Unix timestamps. Adding it here confuses pandas about what you're trying to convert.
  • Missing unit specification: By default, pd.to_datetime treats integer inputs as nanoseconds (ns). If your timestamp is in seconds (like the 1546369086 in your working example), pandas will interpret that number as nanoseconds—equivalent to ~1.5 seconds since 1970-01-01, hence the incorrect early date.

Your datetime code works because datetime.datetime.fromtimestamp() expects a second-level timestamp by default, so it correctly reads 1546369086 as seconds since the epoch.

The Fixes

Pick the solution that matches your timestamp's unit:

1. If your timestamps are in seconds (10-digit numbers like 1546369086)

Remove the format parameter and add unit='s' to tell pandas to treat values as seconds:

raw_data['Date'] = pd.to_datetime(raw_data['UNIX Timestamp'], unit='s')

2. If your timestamps are in milliseconds (13-digit numbers like 1546369086000)

Use unit='ms' instead:

raw_data['Date'] = pd.to_datetime(raw_data['UNIX Timestamp'], unit='ms')

Verify the Fix

Let's test with your sample timestamp to confirm it works:

import pandas as pd
sample_ts = 1546369086
print(pd.to_datetime(sample_ts, unit='s'))
# Output: 2019-01-02 00:28:06

This matches the correct result you got from the datetime code.

Quick Note

You don't need to specify origin='1970-01-01' because that's the default epoch for Unix timestamps—pandas uses it automatically when you define the unit parameter.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 03:42:35