Python中pd.to_datetime转换Unix时间戳为日期返回错误结果的问题
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
formatparameter: Theformatargument 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
unitspecification: By default,pd.to_datetimetreats integer inputs as nanoseconds (ns). If your timestamp is in seconds (like the1546369086in 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

