Skip to content

How to get PastDatetime be seen as a datetime on Model instances? #1041

@Mulugruntz

Description

@Mulugruntz

I'm wondering how PastDatetime on a BaseModel can be seen as a normal datetime on an instance of said model.

from datetime import datetime

from pydantic import BaseModel, PastDatetime, Field, __version__

print(__version__)  # 2.10.6


class Foo(BaseModel):
    timestamp: PastDatetime = Field(default_factory=datetime.now)


def do_something(timestamp: datetime | None = None) -> None:
    if timestamp:
        print(timestamp.isoformat())


foo = Foo()

do_something(foo.timestamp)

In PyCharm Pro
image

PyCharm 2024.3.2 (Professional Edition)
Build #PY-243.23654.177, built on January 27, 2025
macOS 14.6.1
Non-Bundled Plugins:
  ...
  com.koxudaxi.pydantic (0.4.16)
  ...

To be noted that mypy file.py --strict shows:

Success: no issues found in 1 source file

This is a clone of pydantic/pydantic#11414

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions