Python datetimes made easy with timezone-aware datetime manipulation and human-readable formatting
—
Core datetime creation, manipulation, and timezone handling functionality. The DateTime class provides timezone-aware datetime objects with extensive methods for creation, conversion, arithmetic, and comparison operations.
Functions for creating DateTime instances from various sources including current time, specific components, strings, and timestamps.
def now(tz: str | Timezone | None = None) -> DateTime:
"""
Get current DateTime in specified timezone.
Parameters:
- tz: Timezone name, Timezone object, or None for UTC
Returns:
DateTime: Current datetime in specified timezone
"""
def datetime(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tz: str | Timezone | None = None,
fold: int = 1,
raise_on_unknown_times: bool = False
) -> DateTime:
"""
Create DateTime from components.
Parameters:
- year: Year (1-9999)
- month: Month (1-12)
- day: Day (1-31)
- hour: Hour (0-23)
- minute: Minute (0-59)
- second: Second (0-59)
- microsecond: Microsecond (0-999999)
- tz: Timezone (defaults to UTC)
- fold: DST fold handling (0 or 1)
- raise_on_unknown_times: Raise exception for ambiguous times
Returns:
DateTime: New DateTime instance
"""
def local(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0
) -> DateTime:
"""
Create DateTime in local timezone.
Returns:
DateTime: DateTime in system local timezone
"""
def naive(
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
fold: int = 1
) -> DateTime:
"""
Create naive DateTime (no timezone).
Returns:
DateTime: Naive DateTime instance
"""
def today(tz: str | Timezone = "local") -> DateTime:
"""
Create DateTime for today at start of day.
Returns:
DateTime: Today at 00:00:00
"""
def tomorrow(tz: str | Timezone = "local") -> DateTime:
"""
Create DateTime for tomorrow at start of day.
Returns:
DateTime: Tomorrow at 00:00:00
"""
def yesterday(tz: str | Timezone = "local") -> DateTime:
"""
Create DateTime for yesterday at start of day.
Returns:
DateTime: Yesterday at 00:00:00
"""Functions for parsing datetime strings in various formats.
def parse(string: str, **options) -> DateTime | Date | Time | Duration:
"""
Parse datetime string automatically detecting format.
Parameters:
- string: Datetime string to parse
- **options: Additional parsing options
Returns:
DateTime | Date | Time | Duration: Parsed temporal object
"""
def from_format(
string: str,
fmt: str,
tz: str | Timezone = 'UTC',
locale: str | None = None
) -> DateTime:
"""
Parse datetime string with specific format.
Parameters:
- string: Datetime string to parse
- fmt: Format string (e.g., 'YYYY-MM-DD HH:mm:ss')
- tz: Timezone for result
- locale: Locale for parsing
Returns:
DateTime: Parsed DateTime
"""
def from_timestamp(timestamp: int | float, tz: str | Timezone = 'UTC') -> DateTime:
"""
Create DateTime from Unix timestamp.
Parameters:
- timestamp: Unix timestamp (seconds since epoch)
- tz: Timezone for result
Returns:
DateTime: DateTime from timestamp
"""Functions for converting standard datetime objects to Pendulum objects.
def instance(obj, tz: str | Timezone | None = None) -> DateTime | Date | Time:
"""
Create Pendulum object from standard datetime/date/time.
Parameters:
- obj: datetime, date, or time object
- tz: Timezone for DateTime objects
Returns:
DateTime | Date | Time: Corresponding Pendulum object
"""Class methods available on the DateTime class for various creation patterns.
class DateTime:
@classmethod
def create(
cls,
year: int,
month: int,
day: int,
hour: int = 0,
minute: int = 0,
second: int = 0,
microsecond: int = 0,
tz: str | Timezone | None = None,
fold: int = 1,
raise_on_unknown_times: bool = False
) -> DateTime:
"""Create DateTime from components (same as module-level datetime())"""
@classmethod
def now(cls, tz: str | Timezone | None = None) -> DateTime:
"""Get current DateTime (same as module-level now())"""
@classmethod
def utcnow(cls) -> DateTime:
"""Get current DateTime in UTC"""
@classmethod
def today(cls) -> DateTime:
"""Get today at start of day in local timezone"""
@classmethod
def instance(cls, dt, tz: str | Timezone | None = None) -> DateTime:
"""Create from standard datetime object"""
@classmethod
def fromtimestamp(cls, timestamp: float, tz: str | Timezone | None = None) -> DateTime:
"""Create from timestamp"""
@classmethod
def utcfromtimestamp(cls, timestamp: float) -> DateTime:
"""Create from timestamp in UTC"""
@classmethod
def fromordinal(cls, ordinal: int) -> DateTime:
"""Create from ordinal day number"""
@classmethod
def combine(cls, date, time, tzinfo=None) -> DateTime:
"""Combine date and time objects"""
@classmethod
def strptime(cls, date_string: str, format: str) -> DateTime:
"""Parse string with format (like datetime.strptime)"""Methods for modifying DateTime instances.
class DateTime:
def set(
self,
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,
tz: str | Timezone | None = None
) -> DateTime:
"""
Set specific components, returning new DateTime.
Returns:
DateTime: New DateTime with specified components
"""
def on(self, year: int, month: int, day: int) -> DateTime:
"""
Set date components.
Returns:
DateTime: New DateTime with specified date
"""
def at(
self,
hour: int,
minute: int = 0,
second: int = 0,
microsecond: int = 0
) -> DateTime:
"""
Set time components.
Returns:
DateTime: New DateTime with specified time
"""
def replace(self, **kwargs) -> DateTime:
"""
Replace components (like standard datetime.replace).
Returns:
DateTime: New DateTime with replaced components
"""
def naive(self) -> DateTime:
"""
Remove timezone information.
Returns:
DateTime: Naive DateTime
"""
def in_timezone(self, tz: str | Timezone) -> DateTime:
"""
Convert to different timezone.
Parameters:
- tz: Target timezone
Returns:
DateTime: DateTime in target timezone
"""
def in_tz(self, tz: str | Timezone) -> DateTime:
"""Alias for in_timezone()"""Methods for adding and subtracting time periods.
class DateTime:
def add(
self,
years: int = 0,
months: int = 0,
weeks: int = 0,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: float = 0,
microseconds: int = 0
) -> DateTime:
"""
Add time period to DateTime.
Returns:
DateTime: New DateTime with added period
"""
def subtract(
self,
years: int = 0,
months: int = 0,
weeks: int = 0,
days: int = 0,
hours: int = 0,
minutes: int = 0,
seconds: float = 0,
microseconds: int = 0
) -> DateTime:
"""
Subtract time period from DateTime.
Returns:
DateTime: New DateTime with subtracted period
"""Methods for moving to specific time periods or boundaries.
class DateTime:
def start_of(self, unit: str) -> DateTime:
"""
Move to start of time unit.
Parameters:
- unit: 'second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'century'
Returns:
DateTime: DateTime at start of specified unit
"""
def end_of(self, unit: str) -> DateTime:
"""
Move to end of time unit.
Parameters:
- unit: 'second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade', 'century'
Returns:
DateTime: DateTime at end of specified unit
"""
def next(self, day_of_week: WeekDay | None = None, keep_time: bool = False) -> DateTime:
"""
Get next occurrence of weekday.
Parameters:
- day_of_week: Target weekday (None for next day)
- keep_time: Whether to preserve time components
Returns:
DateTime: Next occurrence
"""
def previous(self, day_of_week: WeekDay | None = None, keep_time: bool = False) -> DateTime:
"""
Get previous occurrence of weekday.
Parameters:
- day_of_week: Target weekday (None for previous day)
- keep_time: Whether to preserve time components
Returns:
DateTime: Previous occurrence
"""
def first_of(self, unit: str, day_of_week: WeekDay | None = None) -> DateTime:
"""
Get first occurrence in time unit.
Parameters:
- unit: 'month', 'quarter', 'year'
- day_of_week: Specific weekday (None for first day)
Returns:
DateTime: First occurrence in unit
"""
def last_of(self, unit: str, day_of_week: WeekDay | None = None) -> DateTime:
"""
Get last occurrence in time unit.
Parameters:
- unit: 'month', 'quarter', 'year'
- day_of_week: Specific weekday (None for last day)
Returns:
DateTime: Last occurrence in unit
"""
def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> DateTime:
"""
Get nth occurrence of weekday in time unit.
Parameters:
- unit: 'month', 'quarter', 'year'
- nth: Occurrence number (1-5, -1 for last)
- day_of_week: Target weekday
Returns:
DateTime: Nth occurrence
"""
def average(self, dt: DateTime | None = None) -> DateTime:
"""
Get average DateTime between this and another.
Parameters:
- dt: Other DateTime (defaults to now)
Returns:
DateTime: Average DateTime
"""Methods for comparing DateTimes and testing properties.
class DateTime:
def is_local(self) -> bool:
"""Check if timezone is local system timezone"""
def is_utc(self) -> bool:
"""Check if timezone is UTC"""
def is_dst(self) -> bool:
"""Check if daylight saving time is active"""
def is_future(self) -> bool:
"""Check if DateTime is in the future"""
def is_past(self) -> bool:
"""Check if DateTime is in the past"""
def is_leap_year(self) -> bool:
"""Check if year is a leap year"""
def is_long_year(self) -> bool:
"""Check if ISO year has 53 weeks"""
def is_same_day(self, dt: DateTime) -> bool:
"""Check if same calendar day as another DateTime"""
def is_anniversary(self, dt: DateTime | None = None) -> bool:
"""Check if anniversary date (same month/day)"""
def closest(self, *dts: DateTime) -> DateTime:
"""
Get closest DateTime from list.
Parameters:
- *dts: DateTime objects to compare
Returns:
DateTime: Closest DateTime
"""
def farthest(self, *dts: DateTime) -> DateTime:
"""
Get farthest DateTime from list.
Parameters:
- *dts: DateTime objects to compare
Returns:
DateTime: Farthest DateTime
"""Methods for calculating differences and formatting output.
class DateTime:
def diff(self, dt: DateTime | None = None, abs: bool = True) -> Interval:
"""
Calculate difference as Interval.
Parameters:
- dt: Other DateTime (defaults to now)
- abs: Whether to return absolute difference
Returns:
Interval: Time difference
"""
def diff_for_humans(
self,
other: DateTime | None = None,
absolute: bool = False,
locale: str | None = None
) -> str:
"""
Get human-readable difference description.
Parameters:
- other: Other DateTime (defaults to now)
- absolute: Whether to omit ago/from now
- locale: Locale for formatting
Returns:
str: Human-readable difference (e.g., "2 hours ago")
"""Key properties available on DateTime instances.
class DateTime:
@property
def float_timestamp(self) -> float:
"""Unix timestamp as float"""
@property
def int_timestamp(self) -> int:
"""Unix timestamp as integer"""
@property
def offset(self) -> int:
"""UTC offset in seconds"""
@property
def offset_hours(self) -> float:
"""UTC offset in hours"""
@property
def timezone(self) -> Timezone | FixedTimezone:
"""Timezone object"""
@property
def tz(self) -> Timezone | FixedTimezone:
"""Alias for timezone"""
@property
def timezone_name(self) -> str:
"""Timezone name string"""
@property
def age(self) -> int:
"""Age in years from now"""import pendulum
# Current time
now = pendulum.now()
paris_now = pendulum.now('Europe/Paris')
# Specific datetime
dt = pendulum.datetime(2024, 3, 15, 14, 30, 0)
local_dt = pendulum.local(2024, 3, 15, 14, 30, 0)
# From string
parsed = pendulum.parse('2024-03-15T14:30:00Z')
formatted = pendulum.from_format('15/03/2024 14:30', 'DD/MM/YYYY HH:mm')
# From timestamp
from_ts = pendulum.from_timestamp(1710505800)dt = pendulum.now()
# Modify components
new_dt = dt.set(hour=15, minute=30)
date_changed = dt.on(2024, 12, 25)
time_changed = dt.at(9, 0, 0)
# Timezone conversion
utc_dt = dt.in_timezone('UTC')
tokyo_dt = dt.in_timezone('Asia/Tokyo')
# Arithmetic
future = dt.add(days=7, hours=3)
past = dt.subtract(months=2, days=5)
# Period navigation
start_of_month = dt.start_of('month')
end_of_year = dt.end_of('year')
next_monday = dt.next(pendulum.MONDAY)dt1 = pendulum.now()
dt2 = pendulum.now('Europe/Paris')
# Standard comparisons work
if dt1 > dt2:
print("Later")
# Pendulum-specific tests
if dt1.is_future():
print("In the future")
if dt1.is_same_day(dt2):
print("Same day")
# Find closest/farthest
closest = dt1.closest(dt2, pendulum.tomorrow())DateTime provides various string formatting methods for different standards and use cases.
class DateTime:
def to_time_string(self) -> str:
"""Format as time string (HH:mm:ss)"""
def to_datetime_string(self) -> str:
"""Format as datetime string (YYYY-MM-DD HH:mm:ss)"""
def to_day_datetime_string(self) -> str:
"""Format as day, date and time string"""
def to_atom_string(self) -> str:
"""Format as ATOM string"""
def to_cookie_string(self) -> str:
"""Format as COOKIE string"""
def to_iso8601_string(self) -> str:
"""Format as ISO 8601 string"""
def to_rfc822_string(self) -> str:
"""Format as RFC 822 string"""
def to_rfc850_string(self) -> str:
"""Format as RFC 850 string"""
def to_rfc1036_string(self) -> str:
"""Format as RFC 1036 string"""
def to_rfc1123_string(self) -> str:
"""Format as RFC 1123 string"""
def to_rfc2822_string(self) -> str:
"""Format as RFC 2822 string"""
def to_rfc3339_string(self) -> str:
"""Format as RFC 3339 string"""
def to_rss_string(self) -> str:
"""Format as RSS string"""
def to_w3c_string(self) -> str:
"""Format as W3C string"""
def format(self, fmt: str, locale: str | None = None) -> str:
"""Format using custom format string"""
def for_json(self) -> str:
"""JSON serialization (ISO format)"""Properties inherited from Date class and specific to DateTime.
class DateTime:
@property
def day_of_week(self) -> WeekDay:
"""Day of the week (MONDAY=0 through SUNDAY=6)"""
@property
def day_of_year(self) -> int:
"""Day of the year (1-366)"""
@property
def week_of_year(self) -> int:
"""ISO week number of the year"""
@property
def days_in_month(self) -> int:
"""Number of days in the current month"""
@property
def week_of_month(self) -> int:
"""Week number within the month"""
@property
def quarter(self) -> int:
"""Quarter of the year (1-4)"""Additional utility methods for component extraction and compatibility.
class DateTime:
def date(self) -> Date:
"""Extract date component as Date object"""
def time(self) -> Time:
"""Extract time component as Time object"""
def get_offset(self) -> int | None:
"""Get UTC offset in seconds"""
def astimezone(self, tz: datetime.tzinfo | None = None) -> DateTime:
"""Convert to timezone (datetime compatibility)"""
def is_birthday(self, dt: datetime.datetime | None = None) -> bool:
"""Alias for is_anniversary() - check if birthday/anniversary"""class DateTime:
EPOCH: ClassVar[DateTime] # DateTime(1970, 1, 1, tzinfo=UTC)
min: ClassVar[DateTime] # DateTime(1, 1, 1, 0, 0, tzinfo=UTC)
max: ClassVar[DateTime] # DateTime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=UTC)Install with Tessl CLI
npx tessl i tessl/pypi-pendulum