CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pendulum

Python datetimes made easy with timezone-aware datetime manipulation and human-readable formatting

Pending
Overview
Eval results
Files

date-time-components.mddocs/

Date and Time Components

Specialized classes for working with date-only and time-only values. The Date class provides date functionality without time components, while the Time class handles time values without date information.

Capabilities

Date Creation

Functions and methods for creating Date instances.

def date(year: int, month: int, day: int) -> Date:
    """
    Create Date instance.
    
    Parameters:
    - year: Year (1-9999)
    - month: Month (1-12)  
    - day: Day (1-31)
    
    Returns:
    Date: New Date instance
    """

Date Class Methods

Class methods available on the Date class.

class Date:
    @classmethod
    def today(cls) -> Date:
        """Get current date"""
    
    @classmethod
    def fromtimestamp(cls, timestamp: float) -> Date:
        """Create Date from timestamp"""
    
    @classmethod
    def fromordinal(cls, ordinal: int) -> Date:
        """Create Date from ordinal day number"""

Date Instance Methods

Methods for manipulating and working with Date instances.

class Date:
    def set(
        self,
        year: int | None = None,
        month: int | None = None,
        day: int | None = None
    ) -> Date:
        """
        Set date components.
        
        Returns:
        Date: New Date with specified components
        """
    
    def replace(
        self,
        year: int | None = None,
        month: int | None = None,
        day: int | None = None
    ) -> Date:
        """
        Replace date components.
        
        Returns:
        Date: New Date with replaced components
        """
    
    def add(
        self,
        years: int = 0,
        months: int = 0,
        weeks: int = 0,
        days: int = 0
    ) -> Date:
        """
        Add time period to Date.
        
        Returns:
        Date: New Date with added period
        """
    
    def subtract(
        self,
        years: int = 0,
        months: int = 0,
        weeks: int = 0,
        days: int = 0
    ) -> Date:
        """
        Subtract time period from Date.
        
        Returns:
        Date: New Date with subtracted period
        """
    
    def start_of(self, unit: str) -> Date:
        """
        Move to start of time unit.
        
        Parameters:
        - unit: 'week', 'month', 'year', 'decade', 'century'
        
        Returns:
        Date: Date at start of specified unit
        """
    
    def end_of(self, unit: str) -> Date:
        """
        Move to end of time unit.
        
        Parameters:
        - unit: 'week', 'month', 'year', 'decade', 'century'
        
        Returns:
        Date: Date at end of specified unit
        """
    
    def next(self, day_of_week: WeekDay | None = None) -> Date:
        """
        Get next occurrence of weekday.
        
        Parameters:
        - day_of_week: Target weekday (None for next day)
        
        Returns:
        Date: Next occurrence
        """
    
    def previous(self, day_of_week: WeekDay | None = None) -> Date:
        """
        Get previous occurrence of weekday.
        
        Parameters:
        - day_of_week: Target weekday (None for previous day)
        
        Returns:
        Date: Previous occurrence
        """
    
    def first_of(self, unit: str, day_of_week: WeekDay | None = None) -> Date:
        """
        Get first occurrence in time unit.
        
        Parameters:
        - unit: 'month', 'quarter', 'year'
        - day_of_week: Specific weekday (None for first day)
        
        Returns:
        Date: First occurrence in unit
        """
    
    def last_of(self, unit: str, day_of_week: WeekDay | None = None) -> Date:
        """
        Get last occurrence in time unit.
        
        Parameters:
        - unit: 'month', 'quarter', 'year'
        - day_of_week: Specific weekday (None for last day)
        
        Returns:
        Date: Last occurrence in unit
        """
    
    def nth_of(self, unit: str, nth: int, day_of_week: WeekDay) -> Date:
        """
        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:
        Date: Nth occurrence
        """
    
    def average(self, dt: Date | None = None) -> Date:
        """
        Get average Date between this and another.
        
        Parameters:
        - dt: Other Date (defaults to today)
        
        Returns:
        Date: Average Date
        """
    
    def closest(self, *dates: Date) -> Date:
        """
        Get closest Date from list.
        
        Parameters:
        - *dates: Date objects to compare
        
        Returns:
        Date: Closest Date
        """
    
    def farthest(self, *dates: Date) -> Date:
        """
        Get farthest Date from list.
        
        Parameters:
        - *dates: Date objects to compare
        
        Returns:
        Date: Farthest Date
        """
    
    def is_future(self) -> bool:
        """Check if Date is in the future"""
    
    def is_past(self) -> bool:
        """Check if Date 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: Date) -> bool:
        """Check if same day as another Date"""
    
    def is_anniversary(self, dt: Date | None = None) -> bool:
        """Check if anniversary date (same month/day)"""
    
    def is_birthday(self, dt: Date | None = None) -> bool:
        """Alias for is_anniversary()"""
    
    def diff(self, dt: Date | None = None, abs: bool = True) -> Interval:
        """
        Calculate difference as Interval.
        
        Parameters:
        - dt: Other Date (defaults to today)
        - abs: Whether to return absolute difference
        
        Returns:
        Interval: Time difference
        """
    
    def diff_for_humans(
        self,
        other: Date | None = None,
        absolute: bool = False,
        locale: str | None = None
    ) -> str:
        """
        Get human-readable difference description.
        
        Parameters:
        - other: Other Date (defaults to today)
        - absolute: Whether to omit ago/from now
        - locale: Locale for formatting
        
        Returns:
        str: Human-readable difference
        """
    
    def to_date_string(self) -> str:
        """Format as YYYY-MM-DD"""
    
    def to_formatted_date_string(self) -> str:
        """Format as "Dec 25, 2013" """
    
    def format(self, fmt: str, locale: str | None = None) -> str:
        """
        Format using custom format string.
        
        Parameters:
        - fmt: Format pattern
        - locale: Locale for formatting
        
        Returns:
        str: Formatted date string
        """

Date Properties

Properties available on Date instances.

class Date:
    @property
    def day_of_week(self) -> WeekDay:
        """Day of week as WeekDay enum (0-6)"""
    
    @property
    def day_of_year(self) -> int:
        """Day of year (1-366)"""
    
    @property
    def week_of_year(self) -> int:
        """ISO week number (1-53)"""
    
    @property
    def days_in_month(self) -> int:
        """Number of days in month"""
    
    @property
    def week_of_month(self) -> int:
        """Week of month (1-6)"""
    
    @property
    def age(self) -> int:
        """Age in years from today"""
    
    @property
    def quarter(self) -> int:
        """Quarter of year (1-4)"""

Time Creation

Functions and methods for creating Time instances.

def time(
    hour: int,
    minute: int = 0,
    second: int = 0,
    microsecond: int = 0
) -> Time:
    """
    Create Time instance.
    
    Parameters:
    - hour: Hour (0-23)
    - minute: Minute (0-59)
    - second: Second (0-59)
    - microsecond: Microsecond (0-999999)
    
    Returns:
    Time: New Time instance
    """

Time Class Methods

Class methods available on the Time class.

class Time:
    @classmethod
    def instance(cls, t, tz=None) -> Time:
        """
        Create Time from standard time object.
        
        Parameters:
        - t: Standard time object
        - tz: Timezone (ignored for Time objects)
        
        Returns:
        Time: New Time instance
        """

Time Instance Methods

Methods for manipulating and working with Time instances.

class Time:
    def add(
        self,
        hours: int = 0,
        minutes: int = 0,
        seconds: int = 0,
        microseconds: int = 0
    ) -> Time:
        """
        Add time duration to Time.
        
        Returns:
        Time: New Time with added duration
        """
    
    def subtract(
        self,
        hours: int = 0,
        minutes: int = 0,
        seconds: int = 0,
        microseconds: int = 0
    ) -> Time:
        """
        Subtract time duration from Time.
        
        Returns:
        Time: New Time with subtracted duration
        """
    
    def add_timedelta(self, delta) -> Time:
        """
        Add timedelta to Time.
        
        Parameters:
        - delta: timedelta object
        
        Returns:
        Time: New Time with added delta
        """
    
    def subtract_timedelta(self, delta) -> Time:
        """
        Subtract timedelta from Time.
        
        Parameters:
        - delta: timedelta object
        
        Returns:
        Time: New Time with subtracted delta
        """
    
    def replace(
        self,
        hour: int | None = None,
        minute: int | None = None,
        second: int | None = None,
        microsecond: int | None = None,
        tzinfo: bool = True,
        fold: int = 0
    ) -> Time:
        """
        Replace time components.
        
        Returns:
        Time: New Time with replaced components
        """
    
    def closest(self, *times: Time) -> Time:
        """
        Get closest Time from list.
        
        Parameters:
        - *times: Time objects to compare
        
        Returns:
        Time: Closest Time
        """
    
    def farthest(self, *times: Time) -> Time:
        """
        Get farthest Time from list.
        
        Parameters:
        - *times: Time objects to compare
        
        Returns:
        Time: Farthest Time
        """
    
    def diff(self, t: Time | None = None, abs: bool = True) -> Duration:
        """
        Calculate difference as Duration.
        
        Parameters:
        - t: Other Time (defaults to current time)
        - abs: Whether to return absolute difference
        
        Returns:
        Duration: Time difference
        """
    
    def diff_for_humans(
        self,
        other: Time | None = None,
        absolute: bool = False,
        locale: str | None = None
    ) -> str:
        """
        Get human-readable difference description.
        
        Parameters:
        - other: Other Time (defaults to current time)
        - absolute: Whether to omit ago/from now
        - locale: Locale for formatting
        
        Returns:
        str: Human-readable difference
        """
    
    def format(self, fmt: str, locale: str | None = None) -> str:
        """
        Format using custom format string.
        
        Parameters:
        - fmt: Format pattern
        - locale: Locale for formatting
        
        Returns:
        str: Formatted time string
        """

Time Constants

Constants available on the Time class.

class Time:
    min: Time  # 00:00:00
    max: Time  # 23:59:59.999999
    resolution: timedelta  # 1 microsecond

Usage Examples

Working with Dates

import pendulum

# Create dates
today = pendulum.Date.today()
date = pendulum.date(2024, 3, 15)

# Date arithmetic
future_date = date.add(months=6, days=10)
past_date = date.subtract(years=1)

# Navigation
start_month = date.start_of('month')
end_year = date.end_of('year')
next_friday = date.next(pendulum.FRIDAY)

# Properties
print(f"Day of week: {date.day_of_week}")
print(f"Week of year: {date.week_of_year}")
print(f"Quarter: {date.quarter}")

# Comparisons
if date.is_future():
    print("Future date")

# Formatting
print(date.to_date_string())  # 2024-03-15
print(date.to_formatted_date_string())  # Mar 15, 2024
print(date.format('MMMM Do, YYYY'))  # March 15th, 2024

Working with Times

import pendulum

# Create times
time = pendulum.time(14, 30, 15)
current_time = pendulum.Time.instance(datetime.time(9, 0))

# Time arithmetic
later = time.add(hours=2, minutes=30)
earlier = time.subtract(minutes=45)

# Using timedelta
import datetime
delta = datetime.timedelta(hours=1)
adjusted = time.add_timedelta(delta)

# Comparisons
times = [
    pendulum.time(9, 0),
    pendulum.time(14, 30),
    pendulum.time(18, 45)
]
closest = time.closest(*times)

# Formatting
print(time.format('HH:mm:ss'))  # 14:30:15
print(time.format('h:mm A'))    # 2:30 PM

Converting Between Components

import pendulum

# Get components from DateTime
dt = pendulum.now()
date_part = dt.date()
time_part = dt.time()

# Standard datetime compatibility
std_date = dt.date()  # Returns pendulum.Date
std_time = dt.time()  # Returns pendulum.Time

# Create DateTime from Date and Time using standard datetime
import datetime
combined = datetime.datetime.combine(date_part, time_part)
back_to_pendulum = pendulum.instance(combined)

Install with Tessl CLI

npx tessl i tessl/pypi-pendulum

docs

date-time-components.md

datetime-operations.md

duration-intervals.md

formatting-localization.md

index.md

testing-utilities.md

timezone-management.md

tile.json