### Install Pendulum via poetry Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/installation.md Installation command for projects managed with poetry. ```bash $ poetry add pendulum ``` -------------------------------- ### Install Pendulum via Poetry Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst Clone the repository and install dependencies using Poetry. ```bash $ git clone git@github.com:sdispater/pendulum.git $ poetry install ``` -------------------------------- ### Install Pendulum via pip Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/installation.md Standard installation command for the Pendulum library. ```bash $ pip install pendulum ``` -------------------------------- ### Install Pendulum with test helpers Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/installation.md Installs Pendulum with the optional test feature set for time control helpers. ```bash $ pip install pendulum[test] ``` ```bash $ poetry add pendulum[test] ``` -------------------------------- ### Install Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Install Pendulum using pip. This is the standard way to add Python packages to your project. ```bash pip install pendulum ``` -------------------------------- ### Pendulum Formatter Example Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md Demonstrates the use of Pendulum's custom formatter with the `format()` method for a standard date and time string. ```python >>> import pendulum >>> dt = pendulum.datetime(1975, 12, 25, 14, 15, 16) >>> dt.format('YYYY-MM-DD HH:mm:ss') '1975-12-25 14:15:16' ``` -------------------------------- ### Iterate Over Interval Range with Custom Gap Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md The `range()` method accepts an amount to control the gap between iterations. This example iterates every 2 days. ```python >>> for dt in interval.range('days', 2): >>> print(dt) '2000-01-01T00:00:00+00:00' '2000-01-03T00:00:00+00:00' '2000-01-05T00:00:00+00:00' '2000-01-07T00:00:00+00:00' '2000-01-09T00:00:00+00:00' ``` -------------------------------- ### Get Specific Date and Time Strings Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md Pendulum provides convenient methods to get date and time components as strings in various formats. ```python >>> dt.to_date_string() '1975-12-25' ``` ```python >>> dt.to_formatted_date_string() 'Dec 25, 1975' ``` ```python >>> dt.to_time_string() '14:15:16' ``` ```python >>> dt.to_datetime_string() '1975-12-25 14:15:16' ``` ```python >>> dt.to_day_datetime_string() 'Thu, Dec 25, 1975 2:15 PM' ``` -------------------------------- ### Create an Inverted Interval Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md An inverted interval can be created by providing the end DateTime before the start DateTime. The `remaining_days` will be negative. ```python >>> interval = pendulum.interval(end, start) >>> interval.remaining_days -2 ``` -------------------------------- ### Create an Interval Instance Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md Use the `pendulum.interval()` helper function to create an Interval instance from start and end DateTime objects. ```python >>> import pendulum >>> start = pendulum.datetime(2000, 1, 1) >>> end = pendulum.datetime(2000, 1, 31) >>> interval = pendulum.interval(start, end) ``` -------------------------------- ### Get current time Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md Use `pendulum.now()` to get the current time in UTC. You can also specify a timezone to get the current time in that specific timezone. ```python >>> import pendulum >>> now = pendulum.now() ``` ```python >>> now_in_london_tz = pendulum.now('Europe/London') >>> now_in_london_tz.timezone_name 'Europe/London' ``` -------------------------------- ### Arithmetic Operations on Intervals Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md Most arithmetic operations on Interval instances return a Duration, not another Interval. This example shows multiplying an interval by 2. ```python >>> import pendulum >>> dt1 = pendulum.datetime(2016, 8, 7, 12, 34, 56) >>> dt2 = dt1.add(days=6, seconds=34) >>> interval = pendulum.interval(dt1, dt2) >>> interval * 2 Duration(weeks=1, days=5, minutes=1, seconds=8) ``` -------------------------------- ### Get Total Duration in Different Units (Integer) Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Retrieve the total duration as a truncated integer in weeks, days, hours, minutes, or seconds using the `in_xxx()` methods. ```python >>> import pendulum >>> it = pendulum.duration( ... years=2, months=3, ... days=1177, seconds=7284, microseconds=1234 ... ) >>> it.in_weeks() 168 >>> it.in_days() 1997 >>> it.in_hours() 28250 >>> it.in_minutes() 1695001 >>> it.in_seconds() 101700084 ``` -------------------------------- ### Get Total Duration in Different Units (Float) Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Obtain the total duration expressed as a float in weeks, days, hours, minutes, or seconds using the `total_xxx()` methods. ```python >>> import pendulum >>> it = pendulum.duration( ... years=2, months=3, ... days=1177, seconds=7284, microseconds=1234 ... ) # Each method returns a float like the native # total_seconds() method >>> it.total_weeks() 168.15490079569113 >>> it.total_days() 1177.0843055698379 >>> it.total_hours() 28250.02333367611 >>> it.total_minutes() 1695001.4000205665 >>> it.total_seconds() 101700084.001234 ``` -------------------------------- ### Format Duration into Human-Readable Words Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Use the `in_words()` method to get a human-readable string representation of the duration, supporting locale-specific formatting. ```python >>> import pendulum >>> pendulum.set_locale('fr') >>> it = pendulum.duration(days=1177, seconds=7284, microseconds=1234) >>> it.in_words() '168 semaines 1 jour 2 heures 1 minute 24 secondes' >>> print(it) '168 semaines 1 jour 2 heures 1 minute 24 secondes' >>> it.in_words(locale='de') '168 Wochen 1 Tag 2 Stunden 1 Minute 24 Sekunden' ``` -------------------------------- ### Accessing Timezone Objects and Names Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Get the timezone instance and its corresponding name for a given datetime object. This helps in managing timezone-aware operations. ```python # Gets the timezone instance >>> pendulum.now().timezone >>> pendulum.now().tz # Gets the timezone name >>> pendulum.now().timezone_name ``` -------------------------------- ### Create specific day instances Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md Helpers like `today()`, `tomorrow()`, and `yesterday()` create DateTime instances for the respective days at 00:00:00. They accept an optional timezone parameter. ```python >>> now = pendulum.now() >>> print(now) '2016-06-28T16:51:45.978473-05:00' ``` ```python >>> today = pendulum.today() >>> print(today) '2016-06-28T00:00:00-05:00' ``` ```python >>> tomorrow = pendulum.tomorrow('Europe/London') >>> print(tomorrow) '2016-06-29T00:00:00+01:00' ``` ```python >>> yesterday = pendulum.yesterday() >>> print(yesterday) '2016-06-27T00:00:00-05:00' ``` -------------------------------- ### Shift Time Across Transitions Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Shows how adding or subtracting time maintains correct context across daylight saving transitions. ```python >>> import pendulum >>> dt = pendulum.datetime(2013, 3, 31, 1, 59, 59, 999999, tz='Europe/Paris') '2013-03-31T01:59:59.999999+01:00' >>> dt = dt.add(microseconds=1) '2013-03-31T03:00:00+02:00' >>> dt.subtract(microseconds=1) '2013-03-31T01:59:59.999999+01:00' >>> dt = pendulum.datetime(2013, 10, 27, 2, 59, 59, 999999, tz='Europe/Paris', dst_rule=pendulum.PRE_TRANSITION) '2013-10-27T02:59:59.999999+02:00' >>> dt = dt.add(microseconds=1) '2013-10-27T02:00:00+01:00' >>> dt = dt.subtract(microseconds=1) '2013-10-27T02:59:59.999999+02:00' ``` -------------------------------- ### Create a New Locale Directory Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst Use the clock utility to create a new locale directory. This command generates the necessary file structure for a custom locale. ```bash ./clock locale create ``` -------------------------------- ### Set Date with `on()` and Time with `at()` Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/fluent_helpers.md The `on()` method sets the date components (year, month, day), and the `at()` method sets the time components (hour, minute, second). They can be chained together or used independently. ```python >>> dt.on(1975, 5, 21).at(22, 32, 5).to_datetime_string() '1975-05-21 22:32:05' >>> dt.at(10).to_datetime_string() '2016-11-16 10:00:00' >>> dt.at(10, 30).to_datetime_string() '2016-11-16 10:30:00' ``` -------------------------------- ### Modify Datetime Objects Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Use modifier methods to change specific parts of a datetime object, such as setting the start or end of a period. ```python import pendulum date = pendulum.datetime(2023, 1, 15, 10, 30) # Set to start of the day start_of_day = date.start_of("day") print(start_of_day) # Set to end of the month end_of_month = date.end_of("month") print(end_of_month) ``` -------------------------------- ### Custom DateTime Formatting with `format()` Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md Use the `format()` method with custom format tokens for flexible string representation. For localization, refer to the Localization section. ```python >>> dt.format('dddd Do [of] MMMM YYYY HH:mm:ss A') 'Thursday 25th of December 1975 02:15:16 PM' ``` -------------------------------- ### Using `strftime()` for Formatting Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md The standard `strftime()` method is also available for formatting DateTime instances, though Pendulum's `format()` offers more directives. ```python >>> dt.strftime('%A %-d%t of %B %Y %I:%M:%S %p') 'Thursday 25th of December 1975 02:15:16 PM' ``` -------------------------------- ### Normalize DateTime Instances Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Demonstrates how Pendulum automatically handles timezone transitions during datetime creation. ```python >>> import pendulum >>> pendulum.datetime(2013, 3, 31, 2, 30, tz='Europe/Paris') # 2:30 for the 31th of March 2013 does not exist # so pendulum will return the actual time which is 3:30+02:00 '2013-03-31T03:30:00+02:00' >>> pendulum.datetime(2013, 10, 27, 2, 30, tz='Europe/Paris') # Here, 2:30 exists twice in the day so pendulum will # assume that the transition already occurred '2013-10-27T02:30:00+01:00' ``` -------------------------------- ### Compare datetime Subtraction: Native vs. Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Demonstrates the difference in behavior when subtracting datetimes between Python's native datetime and Pendulum, particularly regarding normalization. ```python >>> import pendulum >>> import datetime >>> d1 = datetime.datetime(2012, 1, 1, 1, 2, 3, tzinfo=datetime.UTC) >>> d2 = datetime.datetime(2011, 12, 31, 22, 2, 3, tzinfo=datetime.UTC) >>> delta = d2 - d1 >>> delta.days -1 >>> delta.seconds 75600 >>> d1 = pendulum.datetime(2012, 1, 1, 1, 2, 3) >>> d2 = pendulum.datetime(2011, 12, 31, 22, 2, 3) >>> delta = d2 - d1 >>> delta.days 0 >>> delta.hours -3 ``` -------------------------------- ### Date and Time Formatting Tokens Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md A comprehensive reference of tokens used to format date and time strings in Pendulum. ```APIDOC ## Date and Time Formatting Tokens ### Description This reference lists the tokens supported by Pendulum for formatting date and time values into strings. ### Tokens Reference | Category | Token | Output Example | | :--- | :--- | :--- | | Year | YYYY | 2000, 2013 | | Year | YY | 00, 13 | | Quarter | Q | 1, 2, 3, 4 | | Month | MMMM | January, February | | Month | MM | 01, 12 | | Day of Month | DD | 01, 31 | | Day of Week | dddd | Monday, Tuesday | | Hour | HH | 00, 23 | | Minute | mm | 00, 59 | | Second | ss | 00, 59 | | AM / PM | A | AM, PM | | Timezone | Z | -07:00, +07:00 | | Timestamp | X | 1381685817 | ``` -------------------------------- ### Instantiate Duration with Days, Seconds, and Microseconds Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Create a Pendulum Duration instance using the `duration()` helper with specific values for days, seconds, and microseconds. ```python >>> import pendulum >>> it = pendulum.duration(days=1177, seconds=7284, microseconds=1234) ``` -------------------------------- ### Set Locale for Localization Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Set the locale for localized date and time representations. Ensure the locale is available on your system. ```python import pendulum pendulum.set_locale("fr") date = pendulum.datetime(2023, 1, 1, tz="UTC") print(date.to_formatted_sring()) ``` -------------------------------- ### Register mysqlclient and PyMySQL Adapters for Pendulum DateTime Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/limitations.md Configure `mysqlclient` and `PyMySQL` to correctly handle `pendulum.DateTime` objects. This involves updating their respective conversion dictionaries to use appropriate literal escaping functions. ```python import pendulum import MySQLdb.converters import pymysql.converters MySQLdb.converters.conversions[pendulum.DateTime] = MySQLdb.converters.DateTime2literal pymysql.converters.conversions[pendulum.DateTime] = pymysql.converters.escape_datetime ``` -------------------------------- ### Configure MySQL Adapters for Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst Register custom converters for MySQLdb and PyMySQL to prevent type() check failures when using Pendulum objects. ```python import MySQLdb.converters import pymysql.converters from pendulum import DateTime MySQLdb.converters.conversions[DateTime] = MySQLdb.converters.DateTime2literal pymysql.converters.conversions[DateTime] = pymysql.converters.escape_datetime ``` -------------------------------- ### Use Fluent Helpers for Datetime Manipulation Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Utilize fluent methods for easy modification of datetime objects. These methods return new datetime instances. ```python import pendulum date = pendulum.datetime(2023, 1, 1) # Add days new_date = date.add(days=5) print(new_date) # Set year new_date = date.set(year=2024) print(new_date) # Start of month new_date = date.start_of("month") print(new_date) ``` -------------------------------- ### Create a naive DateTime instance Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md Use `pendulum.naive()` to create a DateTime instance without any timezone information. This is generally not recommended. ```python >>> import pendulum >>> naive = pendulum.naive(2015, 2, 5) >>> naive.timezone None ``` -------------------------------- ### Control Normalization Behavior Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Configures how the library handles non-existent or ambiguous times using dst_rule. ```python >>> import pendulum >>> pendulum.datetime(2013, 3, 31, 2, 30, 0, 0, tz='Europe/Paris', dst_rule=pendulum.PRE_TRANSITION) '2013-03-31T01:30:00+01:00' >>> pendulum.datetime(2013, 10, 27, 2, 30, 0, 0, tz='Europe/Paris', dst_rule=pendulum.PRE_TRANSITION) '2013-10-27T02:30:00+02:00' >>> pendulum.datetime(2013, 3, 31, 2, 30, 0, 0, tz='Europe/Paris', dst_rule=pendulum.TRANSITION_ERROR) # NonExistingTime: The datetime 2013-03-31 02:30:00 does not exist >>> pendulum.datetime(2013, 10, 27, 2, 30, 0, 0, tz='Europe/Paris', dst_rule=pendulum.TRANSITION_ERROR) # AmbiguousTime: The datetime 2013-10-27 02:30:00 is ambiguous. ``` -------------------------------- ### Direct Iteration Over Interval Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md An Interval instance can be directly iterated over, defaulting to a unit of 'days'. ```python >>> for dt in interval: >>> print(dt) ``` -------------------------------- ### Format dates with locales Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/localization.md Use the locale keyword in the format method to specify the language for date strings. ```python >>> import pendulum >>> dt = pendulum.datetime(1975, 5, 21) >>> dt.format('dddd DD MMMM YYYY', locale='de') 'Mittwoch 21 Mai 1975' >>> dt.format('dddd DD MMMM YYYY') 'Wednesday 21 May 1975' ``` -------------------------------- ### Format Datetime Objects to Strings Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Format datetime objects into strings using various predefined formats or custom format tokens. ```python import pendulum date = pendulum.datetime(2023, 1, 1, 12, 30, tz="UTC") # Default format print(date.to_string()) # Custom format print(date.format("YYYY-MM-DD HH:mm:ss A Z")) # Human-readable format print(date.to_formatted_sring()) ``` -------------------------------- ### Calculate Timezone Differences with Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/introduction.md Demonstrates creating timezone-aware datetime objects and calculating the difference in hours between them. ```python >>> import pendulum >>> dt_toronto = pendulum.datetime(2012, 1, 1, tz='America/Toronto') >>> dt_vancouver = pendulum.datetime(2012, 1, 1, tz='America/Vancouver') >>> print(dt_vancouver.diff(dt_toronto).in_hours()) 3 ``` -------------------------------- ### Create a Pendulum Datetime Object Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Instantiate a Pendulum datetime object. You can create it from the current time or specify a date and time. ```python import pendulum date = pendulum.datetime(2023, 1, 1, tz="UTC") print(date) ``` ```python import pendulum date = pendulum.now("UTC") print(date) ``` -------------------------------- ### Pendulum Limitations Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Understand the limitations of the Pendulum library, such as its reliance on system locales and potential performance considerations for very large-scale operations. ```text Pendulum relies on the system's locale settings for certain formatting and parsing operations. Ensure the desired locale is installed and available on your system. While Pendulum is generally performant, extremely high-frequency operations or manipulations of vast numbers of datetime objects might warrant profiling and potential optimization strategies. ``` -------------------------------- ### Create a basic DateTime instance Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md Use `pendulum.datetime()` to create a DateTime instance. By default, it sets the time to 00:00:00 and the timezone to UTC. ```python >>> import pendulum >>> dt = pendulum.datetime(2015, 2, 5) >>> isinstance(dt, datetime) True >>> dt.timezone.name 'UTC' ``` -------------------------------- ### Configure SQLite Adapter for Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst Register a custom adapter for sqlite3 to handle Pendulum DateTime objects correctly, as sqlite3 uses type() checks. ```python from pendulum import DateTime from sqlite3 import register_adapter register_adapter(DateTime, lambda val: val.isoformat(' ')) ``` -------------------------------- ### Register sqlite3 Adapter for Pendulum DateTime Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/limitations.md Register a custom adapter for `pendulum.DateTime` with `sqlite3` to ensure proper serialization. This is necessary because `sqlite3` uses the `type()` function by default. ```python import pendulum from sqlite3 import register_adapter register_adapter(pendulum.DateTime, lambda val: val.isoformat(' ')) ``` -------------------------------- ### Custom Locale File Structure Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst A new locale directory contains custom.py for your modifications and locale.py for CLDR translations. Do not modify locale.py. ```text / - custom.py - locale.py ``` -------------------------------- ### Create DateTime with specified timezone Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md You can specify a timezone using a string or a `Timezone` instance with the `tz` keyword argument. ```python >>> import pendulum >>> pendulum.datetime(2015, 2, 5, tz='Europe/Paris') ``` ```python >>> tz = pendulum.timezone('Europe/Paris') >>> pendulum.datetime(2015, 2, 5, tz=tz) ``` -------------------------------- ### Create DateTime from a standard datetime instance Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md The `pendulum.instance()` function converts a standard Python `datetime.datetime` object into a Pendulum `DateTime` instance. ```python >>> dt = datetime(2008, 1, 1) >>> p = pendulum.instance(dt) >>> print(p) '2008-01-01T00:00:00+00:00' ``` -------------------------------- ### Instantiate Duration with Years and Months Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/duration.md Create a Pendulum Duration instance supporting the specification of years and months, unlike the native timedelta class. ```python >>> import pendulum >>> it = pendulum.duration(years=2, months=3) ``` -------------------------------- ### Use Timezone Library with Standard Datetime Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Demonstrates using Pendulum's timezone conversion with standard Python datetime objects, utilizing the fold attribute. ```python >>> from datetime import datetime >>> from pendulum import timezone >>> paris = timezone('Europe/Paris') >>> dt = datetime(2013, 3, 31, 2, 30) # By default, fold is set to 0 >>> dt = paris.convert(dt) >>> dt.isoformat() '2013-03-31T01:30:00+01:00' >>> dt = datetime(2013, 3, 31, 2, 30, fold=1) >>> dt = paris.convert(dt) >>> dt.isoformat() '2013-03-31T03:30:00+02:00' ``` -------------------------------- ### Parse Datetime Strings Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Parse various string formats into Pendulum datetime objects. Pendulum intelligently guesses the format. ```python import pendulum date = pendulum.parse("2023-01-01T12:00:00+00:00") print(date) ``` ```python import pendulum date = pendulum.parse("2023-01-01") print(date) ``` ```python import pendulum date = pendulum.parse("01/01/2023", strict=True) print(date) ``` -------------------------------- ### Localize human-readable differences Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/difference.md Change the output language globally using set_locale() or locally by passing the locale argument to diff_for_humans(). ```python >>> import pendulum >>> pendulum.set_locale('de') >>> pendulum.now().add(years=1).diff_for_humans() 'in 1 Jahr' >>> pendulum.now().add(years=1).diff_for_humans(locale='fr') 'dans 1 an' ``` -------------------------------- ### Set Date and Time Components Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/fluent_helpers.md Use the `set()` method to modify year, month, day, hour, minute, or second. This returns a new instance with the updated values. ```python >>> import pendulum >>> dt = pendulum.now() >>> dt.set(year=1975, month=5, day=21).to_datetime_string() '1975-05-21 13:45:18' >>> dt.set(hour=22, minute=32, second=5).to_datetime_string() '2016-11-16 22:32:05' ``` -------------------------------- ### Context Manager Time Travel Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/testing.md Use travel helpers as a context manager to automatically revert to the present time after the block executes. ```python >>> import pendulum >>> now = pendulum.now() >>> with pendulum.travel(minutes=5, freeze=True): >>> pendulum.now().diff_for_humans(now) "5 minutes after" >>> pendulum.now().diff_for_humans(now) "a few seconds after" ``` -------------------------------- ### Common Date and Time Format Methods Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md Pendulum offers several methods to format DateTime objects into commonly used string formats. ```python >>> dt = pendulum.now() >>> dt.to_atom_string() '1975-12-25T14:15:16-05:00' ``` ```python >>> dt.to_cookie_string() 'Thursday, 25-Dec-1975 14:15:16 EST' ``` ```python >>> dt.to_iso8601_string() '1975-12-25T14:15:16-0500' ``` ```python >>> dt.to_rfc822_string() 'Thu, 25 Dec 75 14:15:16 -0500' ``` ```python >>> dt.to_rfc850_string() 'Thursday, 25-Dec-75 14:15:16 EST' ``` ```python >>> dt.to_rfc1036_string() 'Thu, 25 Dec 75 14:15:16 -0500' ``` ```python >>> dt.to_rfc1123_string() 'Thu, 25 Dec 1975 14:15:16 -0500' ``` ```python >>> dt.to_rfc2822_string() 'Thu, 25 Dec 1975 14:15:16 -0500' ``` ```python >>> dt.to_rfc3339_string() '1975-12-25T14:15:16-05:00' ``` ```python >>> dt.to_rss_string() 'Thu, 25 Dec 1975 14:15:16 -0500' ``` ```python >>> dt.to_w3c_string() '1975-12-25T14:15:16-05:00' ``` -------------------------------- ### Test Datetime Functionality Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Pendulum provides helpers for testing, such as freezing time to ensure consistent test results. ```python import pendulum with pendulum.test(pendulum.datetime(2023, 1, 1, tz="UTC")): now = pendulum.now("UTC") print(now) assert now == pendulum.datetime(2023, 1, 1, tz="UTC") ``` -------------------------------- ### Perform Common Datetime Operations with Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/README.rst Use Pendulum for timezone-aware datetime creation, arithmetic, and human-readable formatting. ```python >>> import pendulum >>> now_in_paris = pendulum.now('Europe/Paris') >>> now_in_paris '2016-07-04T00:49:58.502116+02:00' # Seamless timezone switching >>> now_in_paris.in_timezone('UTC') '2016-07-03T22:49:58.502116+00:00' >>> tomorrow = pendulum.now().add(days=1) >>> last_week = pendulum.now().subtract(weeks=1) >>> past = pendulum.now().subtract(minutes=2) >>> past.diff_for_humans() '2 minutes ago' >>> delta = past - last_week >>> delta.hours 23 >>> delta.in_words(locale='en') '6 days 23 hours 58 minutes' # Proper handling of datetime normalization >>> pendulum.datetime(2013, 3, 31, 2, 30, tz='Europe/Paris') '2013-03-31T03:30:00+02:00' # 2:30 does not exist (Skipped time) # Proper handling of dst transitions >>> just_before = pendulum.datetime(2013, 3, 31, 1, 59, 59, 999999, tz='Europe/Paris') '2013-03-31T01:59:59.999999+01:00' >>> just_before.add(microseconds=1) '2013-03-31T03:00:00+02:00' ``` -------------------------------- ### Create an Absolute Inverted Interval Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md To ensure an interval is always positive, even with inverted dates, use the `absolute=True` keyword argument during instantiation. ```python >>> interval = pendulum.interval(end, start, absolute=True) >>> interval.remaining_days 2 ``` -------------------------------- ### Check Date/Time Properties with Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/comparison.md Utilize helper methods like `is_past()` and `is_leap_year()` for quick checks. For methods comparing to `now()`, the `now()` instance is created in the same timezone as the object being checked. ```python >>> import pendulum >>> dt = pendulum.now() >>> dt.is_past() >>> dt.is_leap_year() >>> born = pendulum.datetime(1987, 4, 23) >>> not_birthday = pendulum.datetime(2014, 9, 26) >>> birthday = pendulum.datetime(2014, 4, 23) >>> past_birthday = pendulum.now().subtract(years=50) >>> born.is_birthday(not_birthday) False >>> born.is_birthday(birthday) True >>> past_birthday.is_birthday() # Compares to now by default True ``` -------------------------------- ### Parse strings into exact types Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/parsing.md Use the exact=True keyword argument to return the specific type represented by the string, such as Date or Time. ```python >>> import pendulum >>> pendulum.parse('2012-05-03', exact=True) Date(2012, 05, 03) >>> pendulum.parse('12:04:23', exact=True) Time(12, 04, 23) ``` -------------------------------- ### Calculate and Inspect Interval Properties Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md Subtracting two DateTime instances or using the `diff()` method creates an Interval. Access properties like years, months, weeks, and days to understand the duration. Note that `weeks` and `days` properties are aware of DST. ```python >>> import pendulum >>> start = pendulum.datetime(2000, 11, 20) >>> end = pendulum.datetime(2016, 11, 5) >>> interval = end - start >>> interval.years 15 >>> interval.months 11 >>> interval.in_years() 15 >>> interval.in_months() 191 >>> interval.weeks 2 # 832 for the duration >>> interval.days 5829 ``` -------------------------------- ### Iterate Over an Interval Range Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md The `range()` method allows iteration over an interval with a specified unit (e.g., 'days'). By default, it iterates daily. ```python >>> import pendulum >>> start = pendulum.datetime(2000, 1, 1) >>> end = pendulum.datetime(2000, 1, 10) >>> interval = pendulum.interval(start, end) >>> for dt in interval.range('days'): >>> print(dt) '2000-01-01T00:00:00+00:00' '2000-01-02T00:00:00+00:00' '2000-01-03T00:00:00+00:00' '2000-01-04T00:00:00+00:00' '2000-01-05T00:00:00+00:00' '2000-01-06T00:00:00+00:00' '2000-01-07T00:00:00+00:00' '2000-01-08T00:00:00+00:00' '2000-01-09T00:00:00+00:00' '2000-01-10T00:00:00+00:00' ``` -------------------------------- ### Create DateTime in local timezone Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md The `pendulum.local()` helper creates a DateTime instance set to the system's local timezone. ```python >>> import pendulum >>> dt = pendulum.local(2015, 2, 5) >>> print(dt.timezone.name) 'America/Toronto' ``` -------------------------------- ### Local and UTC Timezone Checks Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Verify if a datetime instance represents local time or UTC. This is essential for ensuring correct time comparisons and conversions. ```python # Indicates if the instance is in the same timezone as the local timezone >>> pendulum.now().is_local() True >>> pendulum.now('Europe/London').is_local() False # Indicates if the instance is in the UTC timezone >>> pendulum.now().is_utc() False >>> pendulum.now('Europe/London').is_local() False >>> pendulum.now('UTC').is_utc() True ``` -------------------------------- ### Handle parsing errors with strict mode Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/parsing.md Use strict=False to allow the library to fall back on the dateutil parser for non-standard strings. ```python >>> import pendulum >>> dt = pendulum.parse('31-01-01') Traceback (most recent call last): ... ParserError: Unable to parse string [31-01-01] >>> dt = pendulum.parse('31-01-01', strict=False) >>> print(dt) '2031-01-01T00:00:00+00:00' ``` -------------------------------- ### Accessing Date and Time Attributes Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Retrieve various components of a datetime object as integers. These properties provide granular access to date and time information. ```python >>> import pendulum >>> dt = pendulum.parse('2012-09-05T23:26:11.123789') # These properties specifically return integers >>> dt.year 2012 >>> dt.month 9 >>> dt.day 5 >>> dt.hour 23 >>> dt.minute 26 >>> dt.second 11 >>> dt.microsecond 123789 >>> dt.day_of_week 3 >>> dt.day_of_year 248 >>> dt.week_of_month 1 >>> dt.week_of_year 36 >>> dt.days_in_month 30 ``` ```python >>> dt.timestamp() 1346887571.123789 >>> dt.float_timestamp 1346887571.123789 >>> dt.int_timestamp 1346887571 ``` -------------------------------- ### Access Datetime Attributes and Properties Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Access various components of a datetime object like year, month, day, hour, minute, second, and timezone. ```python import pendulum date = pendulum.datetime(2023, 1, 1, 12, 30, 0, tz="UTC") print(date.year) print(date.month) print(date.day) print(date.hour) print(date.minute) print(date.second) print(date.timezone.name) ``` -------------------------------- ### Set global locale for human-readable differences Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/localization.md Configure the global locale using pendulum.set_locale to affect subsequent diff_for_humans calls. ```python >>> import pendulum >>> pendulum.set_locale('de') >>> pendulum.now().add(years=1).diff_for_humans() 'in 1 Jahr' >>> pendulum.set_locale('en') ``` -------------------------------- ### Create DateTime from a custom format string Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/instantiation.md The `pendulum.from_format()` method parses a string into a DateTime instance using custom format tokens. It also accepts a `tz` argument. ```python >>> dt = pendulum.from_format('1975-05-21 22', 'YYYY-MM-DD HH') >>> print(dt) '1975-05-21T22:00:00+00:00' ``` ```python >>> dt = pendulum.from_format('1975-05-21 22', 'YYYY-MM-DD HH', tz='Europe/London') '1975-05-21T22:00:00+01:00' ``` -------------------------------- ### Calculating Age and Quarter Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Calculate the age of a datetime object relative to the current time in the same timezone and determine the quarter of the year. ```python >>> pendulum.datetime(1975, 5, 21).age 41 # calculated vs now in the same tz >>> dt.quarter 3 ``` -------------------------------- ### Daylight Saving Time (DST) Check Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Determine if a datetime instance is currently observing Daylight Saving Time. This is crucial for accurate time calculations in regions with DST. ```python # Indicates if daylight savings time is on >>> dt = pendulum.datetime(2012, 1, 1, tz='America/Toronto') >>> dt.is_dst() False >>> dt = pendulum.datetime(2012, 9, 1, tz='America/Toronto') >>> dt.is_dst() True ``` -------------------------------- ### Print Default DateTime String Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/string_formatting.md The default string representation of a DateTime instance is its ISO 8601 format. This is automatically used when printing the object. ```python >>> import pendulum >>> dt = pendulum.datetime(1975, 12, 25, 14, 15, 16) >>> print(dt) '1975-12-25T14:15:16+00:00' ``` -------------------------------- ### Switch Timezones Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Converts a datetime instance to a different timezone using in_timezone or in_tz. ```python >>> in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris') '2016-08-07T22:24:30+02:00' >>> in_paris.in_timezone('America/New_York') '2016-08-07T16:24:30-04:00' >>> in_paris.in_tz('Asia/Tokyo') '2016-08-08T05:24:30+09:00' ``` -------------------------------- ### Work with Timezones Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Create datetime objects in specific timezones and convert between them. Pendulum uses the Olson timezone database. ```python import pendulum dt_utc = pendulum.datetime(2023, 1, 1, tz="UTC") dt_ny = dt_utc.in_timezone("America/New_York") print(dt_ny) dt_tokyo = pendulum.datetime(2023, 1, 1, tz="Asia/Tokyo") print(dt_tokyo.to_formatted_sring()) ``` -------------------------------- ### Convert Datetime with DST Rules Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md Overrides the fold attribute using dst_rule to handle transition errors explicitly. ```python >>> import pendulum >>> dt = datetime(2013, 3, 31, 2, 30) # By default, fold is set to 0 >>> dt = paris.convert(dt, dst_rule=pendulum.PRE_TRANSITION) >>> dt.isoformat() '2013-03-31T01:30:00+01:00' >>> dt = paris.convert(dt, dst_rule=pendulum.POST_TRANSITION) >>> dt.isoformat() '2013-03-31T03:30:00+02:00' >>> paris.convert(dt, dst_rule=pendulum.TRANSITION_ERROR) ``` -------------------------------- ### Compare Datetime Objects Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Compare two Pendulum datetime objects using standard comparison operators. Ensure timezones are handled correctly. ```python import pendulum date1 = pendulum.datetime(2023, 1, 1) date2 = pendulum.datetime(2023, 1, 2) print(date1 < date2) print(date1 == date2) print(date1 > date2) ``` -------------------------------- ### Resetting Time Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/testing.md Return the clock to the present time after performing time travel operations. ```python >>> import pendulum >>> now = pendulum.now() >>> pendulum.travel(minutes=5, freeze=True) >>> pendulum.now().diff_for_humans(now) "5 minutes after" >>> pendulum.travel_back() >>> pendulum.now().diff_for_humans(now) "a few seconds after" ``` -------------------------------- ### Timezone Offset Information Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/attributes_properties.md Obtain the timezone offset from UTC in seconds and hours. This is useful for understanding time differences across regions. ```python # Returns an int of seconds difference from UTC (+/- sign included) >>> pendulum.from_timestamp(0).offset 0 >>> pendulum.from_timestamp(0, 'America/Toronto').offset -18000 # Returns a float of hours difference from UTC (+/- sign included) >>> pendulum.from_timestamp(0, 'America/Toronto').offset_hours -5.0 >>> pendulum.from_timestamp(0, 'Australia/Adelaide').offset_hours 9.5 ``` -------------------------------- ### Add and Subtract Time with Pendulum Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/addition_subtraction.md Use the add() and subtract() methods to modify DateTime objects. These methods return new instances and can handle various time units. ```python >>> import pendulum >>> dt = pendulum.datetime(2012, 1, 31) >>> dt.to_datetime_string() '2012-01-31 00:00:00' ``` ```python >>> dt = dt.add(years=5) '2017-01-31 00:00:00' >>> dt = dt.add(years=1) '2018-01-31 00:00:00' >>> dt = dt.subtract(years=1) '2017-01-31 00:00:00' >>> dt = dt.subtract(years=5) '2012-01-31 00:00:00' ``` ```python >>> dt = dt.add(months=60) '2017-01-31 00:00:00' >>> dt = dt.add(months=1) '2017-02-28 00:00:00' >>> dt = dt.subtract(months=1) '2017-01-28 00:00:00' >>> dt = dt.subtract(months=60) '2012-01-28 00:00:00' ``` ```python >>> dt = dt.add(days=29) '2012-02-26 00:00:00' >>> dt = dt.add(days=1) '2012-02-27 00:00:00' >>> dt = dt.subtract(days=1) '2012-02-26 00:00:00' >>> dt = dt.subtract(days=29) '2012-01-28 00:00:00' ``` ```python >>> dt = dt.add(weeks=3) '2012-02-18 00:00:00' >>> dt = dt.add(weeks=1) '2012-02-25 00:00:00' >>> dt = dt.subtract(weeks=1) '2012-02-18 00:00:00' >>> dt = dt.subtract(weeks=3) '2012-01-28 00:00:00' ``` ```python >>> dt = dt.add(hours=24) '2012-01-29 00:00:00' >>> dt = dt.add(hours=1) '2012-02-25 01:00:00' >>> dt = dt.subtract(hours=1) '2012-02-29 00:00:00' >>> dt = dt.subtract(hours=24) '2012-01-28 00:00:00' ``` ```python >>> dt = dt.add(minutes=61) '2012-01-28 01:01:00' >>> dt = dt.add(minutes=1) '2012-01-28 01:02:00' >>> dt = dt.subtract(minutes=1) '2012-01-28 01:01:00' >>> dt = dt.subtract(minutes=24) '2012-01-28 00:37:00' ``` ```python >>> dt = dt.add(seconds=61) '2012-01-28 00:01:01' >>> dt = dt.add(seconds=1) '2012-01-28 00:01:02' >>> dt = dt.subtract(seconds=1) '2012-01-28 00:01:01' >>> dt = dt.subtract(seconds=61) '2012-01-28 00:00:00' ``` ```python >>> dt = dt.add(years=3, months=2, days=6, hours=12, minutes=31, seconds=43) '2015-04-03 12:31:43' >>> dt = dt.subtract(years=3, months=2, days=6, hours=12, minutes=31, seconds=43) '2012-01-28 00:00:00' ``` -------------------------------- ### Add and Subtract Time from Datetime Objects Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Perform addition and subtraction operations with datetimes and durations or other datetime objects. ```python import pendulum date = pendulum.datetime(2023, 1, 1) # Add a duration new_date = date + pendulum.duration(days=5, hours=3) print(new_date) # Subtract a duration new_date = date - pendulum.duration(weeks=1) print(new_date) ``` -------------------------------- ### Correct DST Transition with Convert Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/timezones.md After adding a timedelta that crosses a DST boundary, re-applying the `convert()` method to the Pendulum datetime object ensures it reflects the correct timezone offset. ```python >>> dt = tz.convert(dt) >>> dt.isoformat() '2013-03-31T03:00:00+02:00' ``` -------------------------------- ### Create and Use Duration Objects Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/index.md Represent a period of time using the Duration object. Durations can be used for arithmetic operations. ```python import pendulum duration = pendulum.duration(days=3, hours=12, minutes=30) print(duration) print(duration.in_hours()) ``` -------------------------------- ### Interval Properties Aware of DST Source: https://github.com/python-pendulum/pendulum/blob/master/docs/docs/interval.md Intervals are aware of DST transitions, providing accurate `remaining_days` and `hours` properties. This differs from standard timedelta objects. ```python >>> import pendulum >>> start = pendulum.datetime(2017, 3, 7, tz='America/Toronto') >>> end = start.add(days=6) >>> interval = end - start >>> interval.days 5 >>> interval.seconds 82800 >>> interval.remaining_days 6 >>> interval.hours 0 >>> interval.remaining_seconds 0 ```