skip to content

After moving to pandas 3.0, epoch seconds computed as df['ts'].astype('int64') // 10**9 come out 1000 times too small. Why, and what is the robust fix?

level: seniorimportance: should knowfreq 40%

answer

  1. the unit behind the integers
  2. strings now parse coarser
  3. a dtype suffix tells you
  4. make the code unit-agnostic

basics

~10 s

pandas 3.0 parses strings to microsecond resolution, datetime64[us], instead of always nanoseconds, so astype('int64') yields microseconds. Divide by a Timedelta, or call .dt.as_unit('s') before casting, so the code no longer assumes a unit.

solid answer

~30 s

In pandas 3.0, datetime resolution is inferred: parsed strings become `datetime64[us]` unless they carry nanosecond digits, `unit="s"` epochs stay `datetime64[s]`, and stdlib datetimes keep microseconds. Before 3.0 they were always `datetime64[ns]`, so `astype("int64") // 10**9` gave seconds; now the integers are microseconds and the same code is off by 1000. I check `.dt.unit` and replace the cast with something unit-agnostic: `(ts - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s")`, or `ts.dt.as_unit("s").astype("int64")`. Arithmetic and merges between columns of different units still work, because pandas casts to the finer unit.

code

python · 13 lines
python
import pandas as pd

df = pd.DataFrame({"ts": pd.to_datetime(["2025-03-14 09:00:00", "2025-03-14 09:00:01"])})
print(df["ts"].dt.unit)                            # 'us' in pandas 3.0
print((df["ts"].astype("int64") // 10**9).tolist())  # [1741942, 1741942] wrong

seconds = (df["ts"] - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s")
print(seconds.tolist())                             # [1741942800, 1741942801]
print(df["ts"].dt.as_unit("s").astype("int64").tolist())

fine = pd.Series(pd.to_datetime(["2025-03-14 09:00:00.123456789"]))
print(fine.dt.unit)                                 # 'ns': the string needs it
print((df["ts"] - fine[0]).dtype)                   # timedelta64[ns]

go deeper

for a junior

Know that a datetime column has a unit shown in its dtype, and that pandas 3.0 parses strings to microseconds.

for a middle

Explain the inference table: strings to us, nanosecond strings to ns, unit='s' epochs to s, and how .dt.unit and as_unit read and change it.

for a senior

Find every place that reads raw integers, replace it with Timedelta division or as_unit, and audit dtype assertions and range guards after the upgrade.

for a principal

Decide whether the team pins one unit at ingest or keeps code unit-agnostic, and write that rule into the migration checklist.

## What changed in pandas 3.0 A pandas datetime column stores each value as a 64-bit integer counting **units** since 1970-01-01. The unit is part of the dtype: `datetime64[s]`, `datetime64[ms]`, `datetime64[us]` or `datetime64[ns]`. You can read it with `.dt.unit`. **Before pandas 3.0**, converting strings, stdlib `datetime` objects or integers always produced **nanoseconds**, or raised `OutOfBoundsDatetime` for dates outside roughly 1677 to 2262. **In pandas 3.0, the resolution is inferred** from the input. This applies to `pd.to_datetime`, `pd.to_timedelta`, `pd.date_range`, `pd.Timestamp`, `pd.Timedelta` and the `Series`, `DataFrame` and `Index` constructors: | input | pandas 2.x | pandas 3.0 | |---|---|---| | strings like `"2025-03-14 09:00"` | `ns` (the 2.x `Timestamp` constructor could already give `s` or `ms`) | `us` | | strings with nanosecond digits | `ns` | `ns` | | `to_datetime(ints, unit="s")` | `ns` | `s` | | `to_datetime(ints, unit="ms")` | `ns` | `ms` | | stdlib `datetime` objects | `ns` | `us` | | NumPy `datetime64` values | `ns` | their own unit, kept between `s` and `ns` | The same inference applies to text read by `read_csv` and `read_json`. ## Why the epoch code broke `astype("int64")` exposes the raw integer, and its meaning depends on the unit. On a `datetime64[us]` column, `2025-03-14 09:00` is `1741942800000000` microseconds, so `// 10**9` gives `1741942`, not `1741942800`. Nothing raises; the numbers are just wrong. The whatsnew note for 3.0 names this as the big exception to "most users will not notice": converting to integers gives values 1000 times smaller. ## Robust fixes 1. **Divide by a duration**, which works whatever the unit: ```python (df["ts"] - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s") ``` For a tz-aware column subtract `pd.Timestamp("1970-01-01", tz="UTC")` instead. 2. **Pin the unit before casting**: `df["ts"].dt.as_unit("s").astype("int64")`. `as_unit` accepts `"s"`, `"ms"`, `"us"` and `"ns"`. 3. **Pin it at creation** when a downstream system needs a fixed unit: `.dt.as_unit("ns")` after parsing, or `pd.date_range(..., unit="ns")`. `as_unit` to a coarser unit drops the extra precision by default (`09:00:00.7` becomes `09:00:00`); pass `round_ok=False` to raise `ValueError` instead when information would be lost. Converting to a finer unit can overflow: a `datetime64[us]` value in the year 1500 parses fine in 3.0 but `as_unit("ns")` raises `OutOfBoundsDatetime`. ## What does not break - **Arithmetic and comparison** between columns of different units work, because pandas casts both sides to the finer unit first; a `us` column minus an `ns` timestamp gives a `timedelta64[ns]` result. - **Merging** on datetime keys of different units matches equal instants. - **`concat`** of a `us` and an `ns` column gives an `ns` column. - **`.dt` fields** such as `year` or `hour`, and `strftime` formatting, give the same values. ## What else to audit after the upgrade - **Dtype assertions** in tests or schema checks that compare against `"datetime64[ns]"` now fail; compare `.dt.unit` deliberately or normalise with `as_unit`. - **`to_numpy()`** returns a `datetime64[us]` array, so code that reinterprets its integers has the same bug. - **Integer views** written to other systems, such as a binary format or a database column expecting nanoseconds, need an explicit `as_unit("ns")`. - **Old far-past or far-future dates** that used to raise now parse, so a guard that relied on the exception no longer fires. ## A quick diagnosis routine 1. Print `df.dtypes` or `s.dt.unit` for every datetime column the step touches. 2. Search the code for `astype("int64")`, `.view(`, `to_numpy()` and hard-coded powers of ten next to datetime columns. 3. Replace each with Timedelta division or an explicit `as_unit`, and add a test on one known row, for example that `2025-03-14 09:00` gives `1741942800`. 4. Run the old and new pipeline on the same input and compare the integer outputs. ## In the interview A strong answer names the cause (inferred resolution, `us` from strings), shows the check (`.dt.unit` or the dtype suffix), gives a unit-agnostic fix, and adds that mixed units are safe in arithmetic but not in raw integers. A weak answer blames time zones or says to `astype("datetime64[ns]")` everywhere without knowing why.

  • In pandas 3.0, why can pd.to_datetime(['1500-01-01']) succeed and then fail after .as_unit('ns')?
    The string parses at microsecond resolution, whose range spans far beyond the 1677 to 2262 window of nanoseconds, so the parse succeeds where pandas 2.x raised. Converting to nanoseconds forces the value into that narrow window, and `as_unit("ns")` raises `OutOfBoundsDatetime`.
  • In pandas 3.0, what resolution does pd.to_datetime(ints, unit='ms') produce, and why does it matter?
    It produces `datetime64[ms]`, because integer input keeps the unit it was read in. Any later step that reads raw integers, via `astype("int64")` or `to_numpy()`, gets milliseconds, so the safe pattern is to divide by a `Timedelta` or call `as_unit` explicitly.

  • Says parsed datetimes are always nanoseconds in pandas 3.0
  • Blames time zones for the factor of 1000
  • Thinks subtracting columns of different units raises
  • Fixes it by hard-coding // 10**6 instead of a unit-agnostic expression
  • Believes as_unit('ns') is always safe for any parsed date

Assumes pandas 3.0: datetime resolution is inferred (strings parse to microseconds), whereas pandas 2.x always produced nanosecond datetime64 from strings, datetimes and integers.