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'
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¶
fold
property
¶
Fold attribute for disambiguation during DST transitions (datetime.datetime compatibility).
Functions¶
now
classmethod
¶
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:
today
classmethod
¶
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
¶
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
¶
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
¶
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:
previous
classmethod
¶
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:
parse
classmethod
¶
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:
format ¶
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¶
Mix of escaped tokens and literal text¶
Use Python string literals for special characters¶
to_iso_string ¶
to_date_string ¶
to_time_string ¶
to_datetime_string ¶
to_atom_string ¶
to_cookie_string ¶
from_datetime
classmethod
¶
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:
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.
diff ¶
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 ¶
subtract_duration ¶
start_of ¶
Return the start of the specified time period.
end_of ¶
Return the end of the specified time period.
as_timezone ¶
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:
to_datetime ¶
Return a copy of the underlying datetime.datetime object.
weekday ¶
Return day of week where Monday=0, Sunday=6 (datetime.datetime compatibility).
isoweekday ¶
Return ISO day of week where Monday=1, Sunday=7 (datetime.datetime compatibility).
isoformat ¶
Return ISO 8601 format string (datetime.datetime compatibility).
isocalendar ¶
Return (year, week, weekday) tuple (datetime.datetime compatibility).
timetz ¶
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).
toordinal ¶
Return proleptic Gregorian ordinal (datetime.datetime compatibility).
utcoffset ¶
Return UTC offset (datetime.datetime compatibility).
astimezone ¶
Convert to another timezone (datetime.datetime compatibility).