Skip to content

Latest commit

 

History

History
1930 lines (1310 loc) · 38.2 KB

File metadata and controls

1930 lines (1310 loc) · 38.2 KB

Carbon

rogervila/python_carbon

PyPI version PyPI - Downloads

PHP Carbon library adapted for Python.

A fluent, immutable-style wrapper around Python's datetime that provides a rich, expressive API for creating, comparing, manipulating, and formatting dates and times.

Table of Contents


Installation

pip install python-carbon

Requirements

Quick Start

from python_carbon import Carbon

# Current date and time
now = Carbon.now()
print(now.toDateTimeString())  # e.g. '2026-03-04 14:30:00'

# Parse a date string
dt = Carbon.parse('2025-12-25 10:00:00')
print(dt.toDateString())  # '2025-12-25'

# Fluent manipulation (each call returns a new Carbon instance)
future = Carbon.now().addDays(30).addHours(2).setMinute(0)
print(future.toDateTimeString())

# Comparison
yesterday = Carbon.yesterday()
tomorrow = Carbon.tomorrow()
print(now.between(yesterday, tomorrow))  # True

# Difference
earlier = Carbon.parse('2025-01-01')
later = Carbon.parse('2025-06-15')
print(later.diffInDays(earlier))  # ≈ 165.0

Note: Every mutating method returns a new Carbon instance — the original is never modified.


Class Constants

Day-of-week constants follow Python's datetime.weekday() convention (Monday = 0):

Constant Value
Carbon.MONDAY 0
Carbon.TUESDAY 1
Carbon.WEDNESDAY 2
Carbon.THURSDAY 3
Carbon.FRIDAY 4
Carbon.SATURDAY 5
Carbon.SUNDAY 6

Instantiation

Constructor

Carbon(now: Union[Carbon, datetime, None] = None) -> Carbon

Creates a new Carbon instance.

Argument Type Description
now Carbon, datetime, or None The date to wrap. Defaults to the current date/time when None.
from datetime import datetime
from python_carbon import Carbon

# Current date/time (equivalent to Carbon.now())
c = Carbon()

# From a datetime object
c = Carbon(datetime(2025, 6, 15, 10, 30, 0))

# From another Carbon instance (copy)
c2 = Carbon(c)

Raises ValueError if an unsupported type is passed.


Carbon.parse(date_string)

@staticmethod
Carbon.parse(date_string: str) -> Carbon

Parses a human-readable date string into a Carbon instance. Internally uses dateutil.parser.parse, so it supports a wide variety of formats.

Carbon.parse('2025-12-25')
Carbon.parse('December 25, 2025 3:30 PM')
Carbon.parse('2025-12-25T15:30:00+02:00')

Carbon.now()

@staticmethod
Carbon.now() -> Carbon

Returns a Carbon instance set to the current local date and time.

now = Carbon.now()
print(now.toDateTimeString())  # e.g. '2026-03-04 14:52:35'

Carbon.utcnow()

@staticmethod
Carbon.utcnow() -> Carbon

Returns a Carbon instance set to the current UTC date and time (timezone-aware).

utc = Carbon.utcnow()
print(utc.toDatetime().tzname())  # 'UTC'

Carbon.yesterday()

@staticmethod
Carbon.yesterday() -> Carbon

Returns a Carbon instance set to yesterday's local date and time (current time minus 1 day).

y = Carbon.yesterday()

Carbon.utcyesterday()

@staticmethod
Carbon.utcyesterday() -> Carbon

Returns a Carbon instance set to yesterday's UTC date and time.


Carbon.tomorrow()

@staticmethod
Carbon.tomorrow() -> Carbon

Returns a Carbon instance set to tomorrow's local date and time (current time plus 1 day).

t = Carbon.tomorrow()

Carbon.utctomorrow()

@staticmethod
Carbon.utctomorrow() -> Carbon

Returns a Carbon instance set to tomorrow's UTC date and time.


Carbon.createFromFormat(format_string, date_string)

@staticmethod
Carbon.createFromFormat(format_string: str, date_string: str) -> Carbon

Creates a Carbon instance from a date string matching the given format. Uses Python's strptime format codes.

Argument Type Description
format_string str A strptime-compatible format string (e.g. '%Y-%m-%d').
date_string str The date string to parse.
dt = Carbon.createFromFormat('%Y-%m-%d', '2025-08-18')
dt = Carbon.createFromFormat('%d/%m/%Y %H:%M', '18/08/2025 14:30')

Carbon.createFromTimestamp(timestamp)

@staticmethod
Carbon.createFromTimestamp(timestamp: int) -> Carbon

Creates a Carbon instance from a Unix timestamp (seconds since epoch).

Argument Type Description
timestamp int A Unix timestamp.
dt = Carbon.createFromTimestamp(1629244800)
print(dt.toDateString())  # '2021-08-18'

Properties

timestamp

@property
timestamp -> float

Returns the Unix timestamp as a float. Shorthand for getTimestamp().

ts = Carbon.now().timestamp

micro

@property
micro -> int

Returns the microsecond component as an int. Shorthand for getMicro().

us = Carbon.now().micro

Getters

getYear()

getYear() -> int

Returns the year component.

Carbon.parse('2025-06-15').getYear()  # 2025

getMonth()

getMonth() -> int

Returns the month component (1–12).

Carbon.parse('2025-06-15').getMonth()  # 6

getDay()

getDay() -> int

Returns the day-of-month component (1–31).

Carbon.parse('2025-06-15').getDay()  # 15

getHour()

getHour() -> int

Returns the hour component (0–23).

Carbon.parse('2025-06-15 14:30:00').getHour()  # 14

getMinute()

getMinute() -> int

Returns the minute component (0–59).

Carbon.parse('2025-06-15 14:30:00').getMinute()  # 30

getSecond()

getSecond() -> int

Returns the second component (0–59).

Carbon.parse('2025-06-15 14:30:45').getSecond()  # 45

getMicro()

getMicro() -> int

Returns the microsecond component (0–999999).

Carbon.parse('2025-06-15 14:30:45.123456').getMicro()  # 123456

getTimestamp()

getTimestamp() -> float

Returns the Unix timestamp as a float.

ts = Carbon.parse('2025-01-01 00:00:00').getTimestamp()

getDayOfWeek()

getDayOfWeek() -> int

Returns the day of the week as an integer (Monday = 0, Sunday = 6), using Python's datetime.weekday() convention.

Carbon.parse('2021-08-18').getDayOfWeek()  # 2 (Wednesday)

getDayOfYear()

getDayOfYear() -> int

Returns the day of the year (1–366).

Carbon.parse('2022-01-02').getDayOfYear()  # 2

getWeekOfMonth(start=0)

getWeekOfMonth(start: int = 0) -> int

Returns the week number within the current month.

Argument Type Default Description
start int 0 Starting index for week numbering.
Carbon.parse('2025-03-15').getWeekOfMonth()    # 0-indexed week number
Carbon.parse('2025-03-15').getWeekOfMonth(1)   # 1-indexed week number

getWeekOfYear()

getWeekOfYear() -> int

Returns the week number within the year, using strftime('%W') (weeks start on Monday, first week starts at 0).

Carbon.parse('2022-01-01').getWeekOfYear()  # 0

getQuarter(start=1)

getQuarter(start: int = 1) -> int

Returns the zero-indexed quarter of the year for the current month.

Argument Type Default Description
start int 1 The month that starts the first quarter (e.g. 1 for Jan, 4 for fiscal years starting in April).
Carbon.parse('2025-03-15').getQuarter()   # 0 (Q1: Jan–Mar)
Carbon.parse('2025-05-15').getQuarter()   # 1 (Q2: Apr–Jun)

getQuarters(start=1)

getQuarters(start: int = 1) -> list

Returns a list of four lists, each containing three month numbers, representing the quarters of the year.

Argument Type Default Description
start int 1 The month that starts the first quarter.
Carbon.now().getQuarters()
# [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

Carbon.now().getQuarters(4)
# [[4, 5, 6], [7, 8, 9], [10, 11, 12], [1, 2, 3]]

getDaysInMonth()

getDaysInMonth() -> int

Returns the number of days in the current month.

Carbon.parse('2025-02-10').getDaysInMonth()  # 28
Carbon.parse('2024-02-10').getDaysInMonth()  # 29 (leap year)

getMonthFirstWeekDay()

getMonthFirstWeekDay() -> int

Returns the weekday of the first day of the current month (Monday = 0, Sunday = 6).

Carbon.parse('2025-03-15').getMonthFirstWeekDay()  # weekday of March 1, 2025

Setters

All setters return a new Carbon instance — the original is not modified.

setYear(year)

setYear(year: int) -> Carbon

Returns a new Carbon with the year replaced.

Carbon.parse('2025-06-15').setYear(2030).toDateString()  # '2030-06-15'

setMonth(month)

setMonth(month: int) -> Carbon

Returns a new Carbon with the month replaced (1–12).

Carbon.parse('2025-06-15').setMonth(1).toDateString()  # '2025-01-15'

setDay(day)

setDay(day: int) -> Carbon

Returns a new Carbon with the day replaced (1–31).

Carbon.parse('2025-06-15').setDay(1).toDateString()  # '2025-06-01'

setHour(hour)

setHour(hour: int) -> Carbon

Returns a new Carbon with the hour replaced (0–23).

Carbon.parse('2025-06-15 14:30:00').setHour(8).toTimeString()  # '08:30:00'

setMinute(minute)

setMinute(minute: int) -> Carbon

Returns a new Carbon with the minute replaced (0–59).

Carbon.parse('2025-06-15 14:30:00').setMinute(0).toTimeString()  # '14:00:00'

setSecond(second)

setSecond(second: int) -> Carbon

Returns a new Carbon with the second replaced (0–59).

Carbon.parse('2025-06-15 14:30:45').setSecond(0).toTimeString()  # '14:30:00'

setMicroSecond(microsecond)

setMicroSecond(microsecond: int) -> Carbon

Returns a new Carbon with the microsecond replaced (0–999999).

Carbon.parse('2025-06-15 14:30:45.123456').setMicroSecond(0).getMicro()  # 0

Formatting

format(format_string)

format(format_string: str) -> str

Formats the date using Python's strftime format codes.

Argument Type Description
format_string str A strftime-compatible format string.
Carbon.parse('2025-06-15 14:30:00').format('%Y-%m-%d')      # '2025-06-15'
Carbon.parse('2025-06-15 14:30:00').format('%d/%m/%Y %H:%M') # '15/06/2025 14:30'

toDateTimeString(with_milliseconds=False)

toDateTimeString(with_milliseconds: bool = False) -> str

Returns the date and time as a string in YYYY-MM-DD HH:MM:SS format. If with_milliseconds is True, microseconds are included.

Argument Type Default Description
with_milliseconds bool False Include microseconds in the output.
dt = Carbon.parse('2025-06-15 14:30:45.123456')

dt.toDateTimeString()                       # '2025-06-15 14:30:45'
dt.toDateTimeString(with_milliseconds=True) # '2025-06-15 14:30:45.123456'

toDateString()

toDateString() -> str

Returns the date as a string in YYYY-MM-DD format.

Carbon.parse('2025-06-15 14:30:00').toDateString()  # '2025-06-15'

toTimeString()

toTimeString() -> str

Returns the time as a string in HH:MM:SS format.

Carbon.parse('2025-06-15 14:30:45').toTimeString()  # '14:30:45'

toDatetime()

toDatetime() -> datetime

Returns the underlying Python datetime object.

dt = Carbon.parse('2025-06-15').toDatetime()
isinstance(dt, datetime)  # True

toCookieString()

toCookieString() -> str

Returns the date formatted as a cookie-style string (e.g. 'Wed, 18-Aug-2021 00:00:00 UTC').

Important: The Carbon instance must be timezone-aware. Use Carbon.utcnow() or convert with .utc() first, otherwise a ValueError is raised.

Carbon.utcnow().toCookieString()  # e.g. 'Tue, 04-Mar-2026 13:52:35 UTC'

toISOString()

toISOString() -> str

Returns the date in ISO 8601-like format: YYYY-MM-DDTHH:MM:SS.ffffffZ.

Carbon.parse('2025-06-15 14:30:00').toISOString()
# '2025-06-15T14:30:00.000000Z'

Comparison

All comparison methods accept another Carbon instance and return a bool.

equalTo(carbon)

equalTo(carbon: Carbon) -> bool

Returns True if both instances represent exactly the same date and time (down to microseconds).

a = Carbon.parse('2025-01-01 00:00:00')
b = Carbon.parse('2025-01-01 00:00:00')
a.equalTo(b)  # True

notEqualTo(carbon)

notEqualTo(carbon: Carbon) -> bool

Returns True if the two instances differ in any component.

a = Carbon.parse('2025-01-01')
b = Carbon.parse('2025-01-02')
a.notEqualTo(b)  # True

greaterThan(carbon)

greaterThan(carbon: Carbon) -> bool

Returns True if this instance is after the other (by timestamp).

later = Carbon.parse('2025-06-15')
earlier = Carbon.parse('2025-01-01')
later.greaterThan(earlier)  # True

greaterThanOrEqualTo(carbon)

greaterThanOrEqualTo(carbon: Carbon) -> bool

Returns True if this instance is after or at the same time as the other.


lessThan(carbon)

lessThan(carbon: Carbon) -> bool

Returns True if this instance is before the other.


lessThanOrEqualTo(carbon)

lessThanOrEqualTo(carbon: Carbon) -> bool

Returns True if this instance is before or at the same time as the other.


between(low, high, included=True)

between(low: Carbon, high: Carbon, included: bool = True) -> bool

Returns True if this instance falls between low and high.

Argument Type Default Description
low Carbon Lower bound.
high Carbon Upper bound.
included bool True If True, the bounds are inclusive (>= / <=). If False, exclusive (> / <).
now = Carbon.now()
now.between(Carbon.yesterday(), Carbon.tomorrow())            # True (inclusive)
now.between(Carbon.yesterday(), Carbon.tomorrow(), False)     # True (exclusive)

Carbon.yesterday().between(Carbon.yesterday(), Carbon.tomorrow(), False)  # False

betweenIncluded(low, high)

betweenIncluded(low: Carbon, high: Carbon) -> bool

Returns True if this instance is >= low and <= high (inclusive bounds).


betweenExcluded(low, high)

betweenExcluded(low: Carbon, high: Carbon) -> bool

Returns True if this instance is > low and < high (exclusive bounds).


isSameMinute(carbon, match_date=True)

isSameMinute(carbon: Carbon, match_date: bool = True) -> bool

Checks if both instances share the same minute.

Argument Type Default Description
carbon Carbon The instance to compare.
match_date bool True If True, the full date and hour must also match. If False, only the minute component is compared.
a = Carbon.parse('2025-06-15 14:30:00')
b = Carbon.parse('2025-06-15 14:30:59')
a.isSameMinute(b)  # True

c = Carbon.parse('2026-01-01 08:30:00')
a.isSameMinute(c, match_date=False)  # True (both minute == 30)

isSameHour(carbon, match_date=True)

isSameHour(carbon: Carbon, match_date: bool = True) -> bool

Checks if both instances share the same hour.

Argument Type Default Description
carbon Carbon The instance to compare.
match_date bool True If True, the full date must also match. If False, only the hour component is compared.

isSameDay(carbon, match_date=True)

isSameDay(carbon: Carbon, match_date: bool = True) -> bool

Checks if both instances share the same day.

Argument Type Default Description
carbon Carbon The instance to compare.
match_date bool True If True, year and month must also match. If False, only the day number is compared.

isSameWeek(carbon)

isSameWeek(carbon: Carbon) -> bool

Returns True if both instances fall in the same week of the month.


isSameMonth(carbon, match_date=True)

isSameMonth(carbon: Carbon, match_date: bool = True) -> bool

Checks if both instances share the same month.

Argument Type Default Description
carbon Carbon The instance to compare.
match_date bool True If True, the year must also match. If False, only the month number is compared.

isSameYear(carbon)

isSameYear(carbon: Carbon) -> bool

Returns True if both instances share the same year.


isSameQuarter(carbon, match_date=True)

isSameQuarter(carbon: Carbon, match_date: bool = True) -> bool

Checks if both instances fall in the same quarter.

Argument Type Default Description
carbon Carbon The instance to compare.
match_date bool True If True, the year must also match. If False, only the quarter number is compared.

Checks

Boolean methods to test characteristics of the current date.

isNextYear()

isNextYear() -> bool

Returns True if the instance's year equals current year + 1.


isLastYear()

isLastYear() -> bool

Returns True if the instance's year equals current year - 1.


isNextMonth()

isNextMonth() -> bool

Returns True if the instance's month equals current month + 1.


isLastMonth()

isLastMonth() -> bool

Returns True if the instance's month equals current month - 1.


isStartOfDay()

isStartOfDay() -> bool

Returns True if the time is exactly 00:00:00.

Carbon.parse('2025-06-15 00:00:00').isStartOfDay()  # True
Carbon.parse('2025-06-15 00:00:01').isStartOfDay()  # False

isEndOfDay()

isEndOfDay() -> bool

Returns True if the time is exactly 23:59:59.

Carbon.parse('2025-06-15 23:59:59').isEndOfDay()  # True

isFuture()

isFuture() -> bool

Returns True if the instance is in the future (timestamp > now).

Carbon.tomorrow().isFuture()   # True
Carbon.yesterday().isFuture()  # False

isPast()

isPast() -> bool

Returns True if the instance is in the past (timestamp < now).

Carbon.yesterday().isPast()  # True
Carbon.tomorrow().isPast()   # False

isMonday()

isMonday() -> bool

Returns True if the instance falls on a Monday.


isTuesday()

isTuesday() -> bool

Returns True if the instance falls on a Tuesday.


isWednesday()

isWednesday() -> bool

Returns True if the instance falls on a Wednesday.

Carbon.parse('2021-08-18').isWednesday()  # True

isThursday()

isThursday() -> bool

Returns True if the instance falls on a Thursday.


isFriday()

isFriday() -> bool

Returns True if the instance falls on a Friday.


isSaturday()

isSaturday() -> bool

Returns True if the instance falls on a Saturday.


isSunday()

isSunday() -> bool

Returns True if the instance falls on a Sunday.


isLeapYear()

isLeapYear() -> bool

Returns True if the instance's year is a leap year.

Carbon.parse('2024-01-01').isLeapYear()  # True
Carbon.parse('2025-01-01').isLeapYear()  # False

isWeekend()

isWeekend() -> bool

Returns True if the instance falls on Saturday or Sunday.


isDayOfWeek(weekday)

isDayOfWeek(weekday: int) -> bool

Returns True if the instance matches the given weekday.

Argument Type Description
weekday int The weekday to check (use Carbon.MONDAY through Carbon.SUNDAY).
Carbon.parse('2021-08-18').isDayOfWeek(Carbon.WEDNESDAY)  # True

isLastDayOfMonth()

isLastDayOfMonth() -> bool

Returns True if the instance's day is the last day of its month.

Carbon.parse('2025-02-28').isLastDayOfMonth()  # True
Carbon.parse('2024-02-28').isLastDayOfMonth()  # False (2024 is a leap year → 29 days)
Carbon.parse('2021-08-31').isLastDayOfMonth()  # True

isFirstDayOfMonth()

isFirstDayOfMonth() -> bool

Returns True if the instance's day is 1.

Carbon.parse('2025-03-01').isFirstDayOfMonth()  # True

Addition and Subtraction

All methods return a new Carbon instance.

add(amount, unit)

add(amount: int, unit: str) -> Carbon

A generic addition method. Internally delegates to the matching add{Unit}() method.

Argument Type Description
amount int The amount to add.
unit str The time unit: 'microSeconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', or 'years'.
Carbon.now().add(10, 'years')   # same as addYears(10)
Carbon.now().add(3, 'months')   # same as addMonths(3)

addMicroSeconds(microseconds=1)

addMicroSeconds(microseconds: int = 1) -> Carbon

Adds the given number of microseconds.


addSeconds(seconds=1)

addSeconds(seconds: int = 1) -> Carbon

Adds the given number of seconds.


addMinutes(minutes=1)

addMinutes(minutes: int = 1) -> Carbon

Adds the given number of minutes.


addHours(hours=1)

addHours(hours: int = 1) -> Carbon

Adds the given number of hours.


addDays(days=1)

addDays(days: int = 1) -> Carbon

Adds the given number of days.

Carbon.parse('2025-01-30').addDays(5).toDateString()  # '2025-02-04'

addWeeks(weeks=1)

addWeeks(weeks: int = 1) -> Carbon

Adds the given number of weeks.


addMonths(months=1)

addMonths(months: int = 1) -> Carbon

Adds the given number of months using dateutil.relativedelta, which correctly handles varying month lengths.

Carbon.parse('2025-01-31').addMonths(1).toDateString()  # '2025-02-28'

addYears(years=1)

addYears(years: int = 1) -> Carbon

Adds the given number of years using dateutil.relativedelta.

Carbon.parse('2024-02-29').addYears(1).toDateString()  # '2025-02-28'

sub(amount, unit)

sub(amount: int, unit: str) -> Carbon

A generic subtraction method. Internally delegates to the matching sub{Unit}() method.

Argument Type Description
amount int The amount to subtract.
unit str The time unit (same options as add()).
Carbon.now().sub(10, 'years')   # same as subYears(10)

subMicroSeconds(microseconds=1)

subMicroSeconds(microseconds: int = 1) -> Carbon

Subtracts the given number of microseconds.


subSeconds(seconds=1)

subSeconds(seconds: int = 1) -> Carbon

Subtracts the given number of seconds.


subMinutes(minutes=1)

subMinutes(minutes: int = 1) -> Carbon

Subtracts the given number of minutes.


subHours(hours=1)

subHours(hours: int = 1) -> Carbon

Subtracts the given number of hours.


subDays(days=1)

subDays(days: int = 1) -> Carbon

Subtracts the given number of days.


subWeeks(weeks=1)

subWeeks(weeks: int = 1) -> Carbon

Subtracts the given number of weeks.


subMonths(months=1)

subMonths(months: int = 1) -> Carbon

Subtracts the given number of months.


subYears(years=1)

subYears(years: int = 1) -> Carbon

Subtracts the given number of years.


Difference

Methods to compute the difference between two Carbon instances.

difference(carbon)

difference(carbon: Carbon) -> dict

Returns a dictionary with a human-readable breakdown of the difference using dateutil.relativedelta.

Returned keys: years, months, days, leapdays, hours, minutes, seconds, microseconds.

earlier = Carbon.parse('2021-01-01 00:00:00.000000')
later = Carbon.parse('2022-03-04 05:06:07.123456')

diff = later.difference(earlier)
# {
#     'years': 1,
#     'months': 2,
#     'days': 3,
#     'leapdays': 0,
#     'hours': 5,
#     'minutes': 6,
#     'seconds': 7,
#     'microseconds': 123456
# }

diffIn(unit, carbon)

diffIn(unit: str, carbon: Carbon) -> int | float

A generic difference method. Delegates to the matching diffIn{Unit}() method.

Argument Type Description
unit str The time unit: 'microseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks', 'months', or 'years'.
carbon Carbon The instance to compare against.
later.diffIn('days', earlier)    # float: total days
later.diffIn('years', earlier)   # int: 1

diffInMicroseconds(carbon)

diffInMicroseconds(carbon: Carbon) -> int

Returns the difference in microseconds as an int.


diffInSeconds(carbon)

diffInSeconds(carbon: Carbon) -> float

Returns the difference in seconds as a float.


diffInMinutes(carbon)

diffInMinutes(carbon: Carbon) -> float

Returns the difference in minutes as a float.


diffInHours(carbon)

diffInHours(carbon: Carbon) -> float

Returns the difference in hours as a float.


diffInDays(carbon)

diffInDays(carbon: Carbon) -> float

Returns the difference in days as a float.

a = Carbon.parse('2025-01-01')
b = Carbon.parse('2025-01-10')
b.diffInDays(a)  # 9.0

diffInWeeks(carbon)

diffInWeeks(carbon: Carbon) -> float

Returns the difference in weeks as a float.


diffInMonths(carbon)

diffInMonths(carbon: Carbon) -> int

Returns the total difference in months as an int (years × 12 + months component from relativedelta).

a = Carbon.parse('2021-01-01')
b = Carbon.parse('2022-03-04')
b.diffInMonths(a)  # 14

diffInYears(carbon)

diffInYears(carbon: Carbon) -> int

Returns the difference in whole years as an int.


Converters

utc()

utc() -> Carbon

Converts the instance to UTC. The instance must already carry timezone information (e.g., from Carbon.parse() with timezone offset).

local = Carbon.parse('2021-08-18T10:00:00+02:00')
utc = local.utc()

utc.toDateTimeString()            # '2021-08-18 08:00:00'
utc.toDatetime().tzname()         # 'UTC'

Modifiers

Methods that move a Carbon instance to the boundary of a given time period. All return a new Carbon instance.

startOf(unit) / endOf(unit)

startOf(unit: str) -> Carbon
endOf(unit: str) -> Carbon

Generic boundary methods that delegate to the specific startOf{Unit}() / endOf{Unit}() methods.

Argument Type Description
unit str 'second', 'minute', 'hour', 'day', 'week', 'month', or 'year'.
Carbon.now().startOf('minute')  # same as startOfMinute()
Carbon.now().endOf('day')       # same as endOfDay()

startOfSecond() / endOfSecond()

startOfSecond() -> Carbon   # microsecond set to 0
endOfSecond() -> Carbon     # microsecond set to 999999

startOfMinute() / endOfMinute()

startOfMinute() -> Carbon   # second=0, microsecond=0
endOfMinute() -> Carbon     # second=59, microsecond=999999

startOfHour() / endOfHour()

startOfHour() -> Carbon     # minute=0, second=0, microsecond=0
endOfHour() -> Carbon       # minute=59, second=59, microsecond=999999

startOfDay() / endOfDay()

startOfDay() -> Carbon      # 00:00:00.000000
endOfDay() -> Carbon        # 23:59:59.999999
dt = Carbon.parse('2025-06-15 14:30:45')
dt.startOfDay().toDateTimeString()  # '2025-06-15 00:00:00'
dt.endOfDay().toDateTimeString()    # '2025-06-15 23:59:59'

startOfWeek() / endOfWeek()

startOfWeek() -> Carbon     # Monday 00:00:00.000000
endOfWeek() -> Carbon       # Sunday 23:59:59.999999

Weeks start on Monday (ISO convention).

dt = Carbon.parse('2021-08-18 14:15:16.123456')   # Wednesday
dt.startOfWeek().toDateTimeString(True)  # '2021-08-16 00:00:00.000000' (Monday)
dt.endOfWeek().toDateTimeString(True)    # '2021-08-22 23:59:59.999999' (Sunday)

startOfMonth() / endOfMonth()

startOfMonth() -> Carbon    # 1st day of month, 00:00:00.000000
endOfMonth() -> Carbon      # last day of month, 23:59:59.999999
dt = Carbon.parse('2025-03-15 10:00:00')
dt.startOfMonth().toDateString()  # '2025-03-01'
dt.endOfMonth().toDateString()    # '2025-03-31'

startOfYear() / endOfYear()

startOfYear() -> Carbon     # January 1, 00:00:00.000000
endOfYear() -> Carbon       # December 31, 23:59:59.999999
dt = Carbon.parse('2021-08-18 14:15:16.123456')
dt.startOfYear().toDateTimeString(True)  # '2021-01-01 00:00:00.000000'
dt.endOfYear().toDateTimeString(True)    # '2021-12-31 23:59:59.999999'

Next Weekday

next(weekday=None)

next(weekday: int = None) -> Carbon

Returns a Carbon instance advanced to the next occurrence of the given weekday. The time of day is preserved.

Argument Type Default Description
weekday int or None None Target weekday (Carbon.MONDAY through Carbon.SUNDAY). Defaults to the current weekday if None.
base = Carbon.parse('2021-08-18 12:34:56')     # Wednesday
base.next(Carbon.MONDAY).toDateString()        # '2021-08-23'
base.next(Carbon.FRIDAY).toDateString()        # '2021-08-27'

nextMonday()nextSunday()

Convenience shortcuts:

nextMonday() -> Carbon
nextTuesday() -> Carbon
nextWednesday() -> Carbon
nextThursday() -> Carbon
nextFriday() -> Carbon
nextSaturday() -> Carbon
nextSunday() -> Carbon
base = Carbon.parse('2021-08-18 12:34:56')   # Wednesday
base.nextMonday().toDateTimeString()          # '2021-08-23 12:34:56'
base.nextSunday().toDateTimeString()          # '2021-08-29 12:34:56'

datetime and timedelta Proxies

Static methods that directly expose Python's datetime and timedelta constructors for convenience.

Carbon.datetime(2025, 6, 15, 10, 30)  # datetime(2025, 6, 15, 10, 30)
Carbon.timedelta(days=1)              # timedelta(days=1)

Proxy Attributes and Methods

Carbon proxies attribute access to the underlying datetime object via __getattr__. This means you can access any datetime attribute or method directly on a Carbon instance:

dt = Carbon.parse('2021-08-18')

dt.year          # 2021   (datetime attribute)
dt.month         # 8
dt.weekday()     # 2      (datetime method, via proxy)
dt.strftime('%Y-%m')  # '2021-08' (datetime method, via proxy)

If the requested attribute does not exist on the underlying datetime, an AttributeError is raised.


License

This project is open-sourced software licensed under the MIT license.

Check the original project source for more details.