Skip to content

Please reconsider 'guessing' whether a timestamp is in milliseconds or seconds #7940

@ariebovenberg

Description

@ariebovenberg

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The following surprising behavior recently tripped me up. When parsing datetimes from unix timestamps, Pydantic
determines automagically whether you mean seconds or milliseconds:

(from the docs)

int or float; assumed as Unix time, i.e. seconds (if >= -2e10 and <= 2e10) or
milliseconds (if < -2e10or > 2e10) since 1 January 1970

This seems sensible at first...but if you're working with milliseconds, Pydantic will decide that most timestamps in 1970 and 1969 are just too small, and they will be interpreted as seconds instead — leading to wildly different times.

While most Pydantic users won't encounter this, it is not a stretch to imagine some Pydantic users are handling data from the 1970s and their validation library, ironically, is silently changing their timestamps.

If you'd rather not change this, please consider adding a big red warning to the docs on the implications of this behavior on timestamps in 1970 and 1969.

Example Code

from datetime import datetime
from pydantic import BaseModel

class Foo(BaseModel):
    a: datetime

# some timestamps in ms
recent = datetime(2023, 10, 4, 12, 22).timestamp() * 1000
apollo17_launch = datetime(1972, 12, 7, 5, 33).timestamp() * 1000
apollo13_launch = datetime(1970, 4, 11, 19, 13).timestamp() * 1000

print(Foo(a=recent))           # 2023-10-04 (correct)
print(Foo(a=apollo17_launch))  # 1972-12-07 (correct)
print(Foo(a=apollo13_launch))  # 2245-11-14 (INCORRECT)

Python, Pydantic & OS Version

pydantic version: 2.4.2
        pydantic-core version: 2.10.1
          pydantic-core build: profile=release pgo=false
                 install path: /Users/arie/.pyenv/versions/3.12.0/envs/sandbox312/lib/python3.12/site-packages/pydantic
               python version: 3.12.0 (main, Oct  3 2023, 08:33:34) [Clang 15.0.0 (clang-1500.0.40.1)]
                     platform: macOS-14.0-arm64-arm-64bit
             related packages: typing_extensions-4.8.0

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions