Skip to content

DateTime

The DateTime class provides comprehensive datetime functionality with timezone support.

carbonic.core.datetime.DateTime dataclass

DateTime(
    year: int,
    month: int,
    day: int,
    hour: int = 0,
    minute: int = 0,
    second: int = 0,
    microsecond: int = 0,
    tz: str | None = "UTC",
)

Immutable datetime object with fluent API and timezone support.

The DateTime class provides a modern, type-safe wrapper around Python's datetime with comprehensive datetime manipulation. All operations return new instances, maintaining immutability.

Attributes:

Name Type Description
_dt datetime

Internal datetime.datetime object storing the actual datetime value

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, 0, tz="UTC")
>>> dt.add(hours=2).format("Y-m-d H:i:s")
'2024-01-15 16:30:00'
>>> now = DateTime.now("America/New_York")
>>> now.to_date_string()
'2024-01-15'

Initialize a new DateTime instance.

Parameters:

Name Type Description Default
year int

Year (e.g., 2024)

required
month int

Month (1-12)

required
day int

Day of month (1-31)

required
hour int

Hour (0-23, default: 0)

0
minute int

Minute (0-59, default: 0)

0
second int

Second (0-59, default: 0)

0
microsecond int

Microsecond (0-999999, default: 0)

0
tz str | None

Timezone string (default: "UTC", None for naive datetime)

'UTC'

Raises:

Type Description
ValueError

If any datetime component is invalid

ZoneInfoNotFoundError

If timezone string is invalid

Attributes

year property

year: int

The year component (e.g., 2024).

month property

month: int

The month component (1-12).

day property

day: int

The day of month component (1-31).

hour property

hour: int

The hour component (0-23).

minute property

minute: int

The minute component (0-59).

second property

second: int

The second component (0-59).

microsecond property

microsecond: int

The microsecond component (0-999999).

tzinfo property

tzinfo: tzinfo | None

The timezone info, or None for naive datetime.

fold property

fold: int

Fold attribute for disambiguation during DST transitions (datetime.datetime compatibility).

Functions

now classmethod

now(tz: str | None = 'UTC') -> DateTime

Create a DateTime instance for the current moment.

Parameters:

Name Type Description Default
tz str | None

Timezone string (default: "UTC", None for system local time)

'UTC'

Returns:

Type Description
DateTime

DateTime instance representing the current moment

Examples:

>>> DateTime.now()  # Current time in UTC
>>> DateTime.now("America/New_York")  # Current time in NY timezone
>>> DateTime.now(None)  # Current local time (naive)

today classmethod

today(tz: str | None = 'UTC') -> DateTime

Get the current date at 00:00:00 in the specified timezone.

Parameters:

Name Type Description Default
tz str | None

Timezone string (default: "UTC")

'UTC'

Returns:

Type Description
DateTime

DateTime object representing today at midnight

tomorrow classmethod

tomorrow(tz: str | None = 'UTC') -> DateTime

Get tomorrow's date at 00:00:00 in the specified timezone.

Parameters:

Name Type Description Default
tz str | None

Timezone string (default: "UTC")

'UTC'

Returns:

Type Description
DateTime

DateTime object representing tomorrow at midnight

yesterday classmethod

yesterday(tz: str | None = 'UTC') -> DateTime

Get yesterday's date at 00:00:00 in the specified timezone.

Parameters:

Name Type Description Default
tz str | None

Timezone string (default: "UTC")

'UTC'

Returns:

Type Description
DateTime

DateTime object representing yesterday at midnight

next classmethod

next(unit: str, count: int = 1, tz: str | None = 'UTC') -> DateTime

Get a datetime in the future relative to now.

Parameters:

Name Type Description Default
unit str

Time unit ("second", "minute", "hour", "day", "week", "month", "quarter", "year")

required
count int

Number of units to add (default: 1)

1
tz str | None

Timezone string (default: "UTC")

'UTC'

Returns:

Type Description
DateTime

DateTime object in the future

Examples:

>>> DateTime.next("day")      # Tomorrow
>>> DateTime.next("week", 2)  # 2 weeks from now
>>> DateTime.next("month")    # Next month

previous classmethod

previous(unit: str, count: int = 1, tz: str | None = 'UTC') -> DateTime

Get a datetime in the past relative to now.

Parameters:

Name Type Description Default
unit str

Time unit ("second", "minute", "hour", "day", "week", "month", "quarter", "year")

required
count int

Number of units to subtract (default: 1)

1
tz str | None

Timezone string (default: "UTC")

'UTC'

Returns:

Type Description
DateTime

DateTime object in the past

Examples:

>>> DateTime.previous("day")      # Yesterday
>>> DateTime.previous("week", 2)  # 2 weeks ago
>>> DateTime.previous("month")    # Last month

parse classmethod

parse(s: str, fmt: str | None = None, tz: str | None = None) -> DateTime

Parse a datetime string into a DateTime object.

Parameters:

Name Type Description Default
s str

The datetime string to parse. Supports: - ISO 8601 formats (2024-01-15T14:30:00Z) - Custom formats when fmt is provided

required
fmt str | None

Optional format string. If None, auto-detect format. Supports both strftime (%Y-%m-%d %H:%M:%S) and Carbon (Y-m-d H:i:s) formats.

None
tz str | None

Optional timezone. If provided, applies to naive parsed datetimes.

None

Returns:

Type Description
DateTime

DateTime object

Raises:

Type Description
ParseError

If the string cannot be parsed

Examples:

>>> DateTime.parse("2024-01-15T14:30:00Z")

strftime

strftime(fmt: str) -> str

Format datetime using strftime format string.

format

format(fmt: str, *, locale: str | None = None) -> str

Format datetime using Carbon-style format string.

Uses Carbon-style tokens for flexible datetime formatting. Escape Carbon tokens with curly braces like {Y} to include them literally. Use Python string literals for special characters like \n, \t, \r.

Format Tokens
Token Description Example
Date
Y 4-digit year 2024
y 2-digit year 24
m Month with leading zero 01, 12
n Month without leading zero 1, 12
d Day with leading zero 01, 31
j Day without leading zero 1, 31
S Ordinal suffix st, nd, rd, th
F Full month name (localized) January, enero
M Short month name (localized) Jan, ene
l Full day name (localized) Monday, lunes
D Short day name (localized) Mon, lun
Time
H Hour 24-format with leading zero 00, 23
G Hour 24-format without leading zero 0, 23
h Hour 12-format with leading zero 01, 12
g Hour 12-format without leading zero 1, 12
i Minutes with leading zero 00, 59
s Seconds with leading zero 00, 59
A AM/PM uppercase AM, PM
a am/pm lowercase am, pm
u Microseconds (6 digits) 000000, 123456
v Milliseconds (3 digits) 000, 123
Timezone
T Timezone abbreviation UTC, EST
O Timezone offset +0000, +0200
P Timezone offset with colon +00:00, +02:00
Z Timezone offset in seconds 0, 7200
Combined
c ISO 8601 datetime 2024-01-15T14:30:45+00:00
r RFC 2822 datetime Mon, 15 Jan 2024 14:30:45 +0000

Parameters:

Name Type Description Default
fmt str

Carbon-style format string with tokens above

required
locale str | None

Locale code for localized month/day names (default: English) Supported: en, pl, es, fr, de, pt

None

Returns:

Type Description
str

Formatted datetime string

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, 45, tz="UTC")
>>> dt.format("Y-m-d H:i:s")
'2024-01-15 14:30:45'
>>> dt.format("l, F j, Y")
'Monday, January 15, 2024'
>>> dt.format("l, F j, Y", locale="es")
'lunes, enero 15, 2024'
>>> dt.format("H:i A (T)")
'14:30 PM (UTC)'
Escaping Carbon tokens with curly braces
>>> dt.format("{Y} = Y")
'Y = 2024'
Mix of escaped tokens and literal text
>>> dt.format("{Y}-{m}-{d} = Y-m-d")
'Y-m-d = 2024-01-15'
Use Python string literals for special characters
>>> dt.format("Y-m-d\nH:i:s")  # \n in Python string
'2024-01-15\n14:30:45'

to_iso_string

to_iso_string() -> str

Return ISO 8601 string (2025-09-23T14:30:45+00:00).

Returns:

Type Description
str

ISO 8601 formatted datetime string with timezone

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, tz="UTC")
>>> dt.to_iso_string()
'2024-01-15T14:30:00+00:00'

to_date_string

to_date_string() -> str

Return date string (2025-09-23).

Returns:

Type Description
str

Date portion formatted as YYYY-MM-DD

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30)
>>> dt.to_date_string()
'2024-01-15'

to_time_string

to_time_string() -> str

Return time string (14:30:45).

Returns:

Type Description
str

Time portion formatted as HH:MM:SS

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, 45)
>>> dt.to_time_string()
'14:30:45'

to_datetime_string

to_datetime_string() -> str

Return datetime string (2025-09-23 14:30:45).

Returns:

Type Description
str

Datetime formatted as YYYY-MM-DD HH:MM:SS (no timezone)

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, 45)
>>> dt.to_datetime_string()
'2024-01-15 14:30:45'

to_atom_string

to_atom_string() -> str

Return Atom/RSS datetime string (ISO 8601).

Returns:

Type Description
str

ISO 8601 formatted string suitable for Atom/RSS feeds

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, tz="UTC")
>>> dt.to_atom_string()
'2024-01-15T14:30:00+00:00'
to_cookie_string() -> str

Return cookie datetime string (Tue, 23-Sep-2025 14:30:45 UTC).

Returns:

Type Description
str

Cookie-compatible datetime string format

Examples:

>>> dt = DateTime(2024, 1, 15, 14, 30, tz="UTC")
>>> dt.to_cookie_string()
'Mon, 15-Jan-2024 14:30:00 UTC'

from_datetime classmethod

from_datetime(dt: datetime) -> DateTime

Create a DateTime from a standard Python datetime object.

Parameters:

Name Type Description Default
dt datetime

Python datetime.datetime object to convert

required

Returns:

Type Description
DateTime

New DateTime instance preserving timezone information

Examples:

>>> import datetime
>>> dt = datetime.datetime(2024, 1, 15, 14, 30)
>>> carbonic_dt = DateTime.from_datetime(dt)

add

add(
    *,
    days: int = 0,
    hours: int = 0,
    minutes: int = 0,
    seconds: int = 0,
    months: int = 0,
    years: int = 0,
) -> DateTime

Add time components to this datetime.

subtract

subtract(**kwargs: int) -> DateTime

Subtract time components from this datetime.

diff

diff(other: DateTime, *, absolute: bool = False) -> Duration

Calculate difference between this datetime and another datetime.

Parameters:

Name Type Description Default
other DateTime

The other datetime to compare with

required
absolute bool

If True, return absolute difference (always positive)

False

Returns:

Type Description
Duration

Duration representing the difference

add_duration

add_duration(duration: Duration) -> DateTime

Add a Duration to this DateTime.

Parameters:

Name Type Description Default
duration Duration

The Duration to add

required

Returns:

Type Description
DateTime

New DateTime with the duration added

subtract_duration

subtract_duration(duration: Duration) -> DateTime

Subtract a Duration from this DateTime.

Parameters:

Name Type Description Default
duration Duration

The Duration to subtract

required

Returns:

Type Description
DateTime

New DateTime with the duration subtracted

start_of

start_of(
    unit: Literal["minute", "hour", "day", "week", "month", "quarter", "year"],
) -> DateTime

Return the start of the specified time period.

end_of

end_of(
    unit: Literal["minute", "hour", "day", "week", "month", "quarter", "year"],
) -> DateTime

Return the end of the specified time period.

as_timezone

as_timezone(tz: str | None) -> DateTime

Convert this DateTime to a different timezone.

This method converts a timezone-aware DateTime to a different timezone, representing the same moment in time. It can also convert to a naive datetime by passing None as the timezone.

Parameters:

Name Type Description Default
tz str | None

Target timezone string (e.g., "America/New_York", "Europe/Warsaw") or None for naive datetime (removes timezone info)

required

Returns:

Type Description
DateTime

New DateTime instance in the target timezone representing the same moment

Raises:

Type Description
ValueError

If this DateTime is naive and target timezone is not None

ZoneInfoNotFoundError

If timezone string is invalid

Examples:

>>> utc_time = DateTime(2024, 1, 15, 14, 30, tz="UTC")
>>> ny_time = utc_time.as_timezone("America/New_York")
>>> # Same moment, different timezone representation
>>> utc_time == ny_time
True
>>> # Convert to naive datetime
>>> naive_time = utc_time.as_timezone(None)

to_date

to_date() -> Date

Convert to carbonic Date object.

to_datetime

to_datetime() -> datetime.datetime

Return a copy of the underlying datetime.datetime object.

weekday

weekday() -> int

Return day of week where Monday=0, Sunday=6 (datetime.datetime compatibility).

isoweekday

isoweekday() -> int

Return ISO day of week where Monday=1, Sunday=7 (datetime.datetime compatibility).

isoformat

isoformat(sep: str = 'T', timespec: str = 'auto') -> str

Return ISO 8601 format string (datetime.datetime compatibility).

isocalendar

isocalendar() -> tuple[int, int, int]

Return (year, week, weekday) tuple (datetime.datetime compatibility).

date

date() -> datetime.date

Return date object with same date (datetime.datetime compatibility).

time

time() -> datetime.time

Return time object with same time (datetime.datetime compatibility).

timetz

timetz() -> datetime.time

Return time object with same time and tzinfo (datetime.datetime compatibility).

replace

replace(
    year: int | None = None,
    month: int | None = None,
    day: int | None = None,
    hour: int | None = None,
    minute: int | None = None,
    second: int | None = None,
    microsecond: int | None = None,
    tzinfo: tzinfo | None | object = ...,
) -> DateTime

Return a DateTime with one or more components replaced (datetime.datetime compatibility).

timetuple

timetuple()

Return time.struct_time (datetime.datetime compatibility).

utctimetuple

utctimetuple()

Return UTC time.struct_time (datetime.datetime compatibility).

toordinal

toordinal() -> int

Return proleptic Gregorian ordinal (datetime.datetime compatibility).

timestamp

timestamp() -> float

Return POSIX timestamp (datetime.datetime compatibility).

utcoffset

utcoffset() -> datetime.timedelta | None

Return UTC offset (datetime.datetime compatibility).

dst

dst() -> datetime.timedelta | None

Return DST offset (datetime.datetime compatibility).

tzname

tzname() -> str | None

Return timezone name (datetime.datetime compatibility).

astimezone

astimezone(tz: tzinfo | None = None) -> DateTime

Convert to another timezone (datetime.datetime compatibility).

ctime

ctime() -> str

Return ctime() style string (datetime.datetime compatibility).