Pandas Timestamp Converter
Pandas uses its own Timestamp class (a subclass of Python's datetime) and stores datetime columns as datetime64[ns] — nanosecond-precision Unix timestamps internally. This means all Pandas datetime values are, at their core, integers counting nanoseconds since January 1, 1970 UTC. Understanding this internal representation is key to efficient Pandas timestamp handling.
Pandas provides the pd.to_datetime() function as the primary way to create datetime values from various inputs, including Unix timestamps in seconds or milliseconds. The unit parameter specifies whether your input is in seconds, milliseconds, microseconds, or nanoseconds.
Pandas timestamp conversion examples
Unix seconds to Pandas Timestamp:
pd.Timestamp(1700000000, unit='s')
→ Timestamp('2023-11-14 22:13:20')
Unix milliseconds to Timestamp:
pd.Timestamp(1700000000000, unit='ms')
Pandas Timestamp to Unix seconds:
pd.Timestamp('2026-04-17').timestamp() # returns float
int(pd.Timestamp('2026-04-17', tz='UTC').timestamp())
Convert a Series of Unix timestamps to datetime:
df['datetime'] = pd.to_datetime(df['unix_ts'], unit='s')
Convert datetime column to Unix seconds:
df['unix_ts'] = df['datetime'].astype('int64') // 10**9 # nanoseconds to seconds
Timezone-aware conversion:
pd.to_datetime(df['unix_ts'], unit='s', utc=True) # returns UTC-aware series
.dt.tz_convert('Europe/Oslo') # convert to Oslo time