Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Openai Openai python Datetime Parse

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure
Last Updated 2026-02-15 00:00 GMT

Overview

Concrete tool for date and datetime parsing provided by the openai-python SDK.

Description

The _datetime_parse module provides parse_datetime() and parse_date() functions adapted from Pydantic v1's datetime parsing logic (without the Pydantic-specific errors). These functions accept strings, bytes, integers, floats, or native date/datetime objects and return proper datetime.datetime or datetime.date instances. String parsing uses regex patterns for ISO 8601 formats (YYYY-MM-DD for dates, YYYY-MM-DDTHH:MM:SS with optional microseconds and timezone for datetimes). Numeric inputs are interpreted as Unix timestamps, with an MS_WATERSHED threshold (2e10) to auto-detect whether the value is in seconds or milliseconds. Timezone parsing supports Z (UTC) and fixed [+-]HH:MM offsets. The module is used as the datetime parser when running with Pydantic v2+, where the v1 parsing utilities are no longer available.

Usage

Use these functions when deserializing API response fields that contain date or datetime values from various formats (ISO strings, Unix timestamps, etc.).

Code Reference

Source Location

Signature

EPOCH = datetime(1970, 1, 1)
MS_WATERSHED = int(2e10)
MAX_NUMBER = int(3e20)

def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: ...
def parse_date(value: Union[date, StrBytesIntFloat]) -> date: ...

Import

from openai._utils._datetime_parse import parse_datetime, parse_date

I/O Contract

Inputs

Name Type Required Description
value datetime / date / str / bytes / int / float Yes The value to parse into a date or datetime object

Outputs

Name Type Description
parse_datetime result datetime.datetime Parsed datetime, possibly with timezone info
parse_date result datetime.date Parsed date

Usage Examples

Basic Usage

from openai._utils._datetime_parse import parse_datetime, parse_date

# Parse ISO 8601 string
dt = parse_datetime("2024-01-15T10:30:00Z")
# datetime(2024, 1, 15, 10, 30, tzinfo=timezone.utc)

# Parse Unix timestamp (seconds)
dt = parse_datetime(1705312200)
# datetime(2024, 1, 15, 10, 30, tzinfo=timezone.utc)

# Parse date string
d = parse_date("2024-01-15")
# date(2024, 1, 15)

# Parse millisecond timestamp (auto-detected via MS_WATERSHED)
dt = parse_datetime(1705312200000)
# datetime(2024, 1, 15, 10, 30, tzinfo=timezone.utc)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment