w3resource

Python Pendulum Module - Exercises, Solutions, and Examples


Python Pendulum Module [34 exercises with solution]


Pendulum is a date and time manipulation library that provides a cleaner and more intuitive interface than the standard "datetime" module. It offers features like a more expressive API, improved timezone support, easier formatting, and parsing of dates and times.

To use Pendulum, you need to install it first using a package manager like pip:

pip install pendulum

Current Date and Time:

1. Write a Python program to print the current date and time using Pendulum module.

Code:

import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Print the current date and time
print("Current Date and Time:", current_datetime) 

Output:

Current Date and Time: 2024-02-02 10:57:16.160411+05:30

Manipulate Date and Time:

2. Write a Python program to create a Pendulum object for tomorrow's date and time using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Calculate the date and time for tomorrow by adding one day
tomorrow_datetime = current_datetime.add(days=1)

# Print the Pendulum object for tomorrow's date and time
print("Pendulum object for tomorrow's date and time:", tomorrow_datetime)

Output:

Pendulum object for tomorrow's date and time: 2024-02-03 11:05:09.411557+05:30

Date Formatting:

3. Write a Python program to format the current date and time as "YYYY-MM-DD HH:mm:ss" using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Format the date and time as "YYYY-MM-DD HH:mm:ss"
formatted_datetime = current_datetime.format('YYYY-MM-DD HH:mm:ss')

# Print the formatted date and time
print("Formatted Date and Time:", formatted_datetime)

Output:

Formatted Date and Time: 2024-02-02 11:12:18

Timezone Support:

4. Write a Python program to create a Pendulum object for the current date and time in the "Europe/London" timezon using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time in the "Europe/London" timezone
london_datetime = pendulum.now('Europe/London')

# Print the Pendulum object for the current date and time in London timezone
print("Pendulum object for the current date and time in London timezone:", london_datetime)

Output:

Pendulum object for the current date and time in London timezone: 2024-02-02 05:45:58.214606+00:00

Convert Timezone:

5. Write a Python program to convert the current date and time from "UTC" to "America/New_York" timezone using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time in UTC
utc_datetime = pendulum.now('UTC')

# Convert the UTC date and time to "America/New_York" timezone
ny_datetime = utc_datetime.in_tz('America/New_York')

# Print the converted Pendulum object
print("Converted date and time to America/New_York timezone:", ny_datetime)

Output:

Converted date and time to America/New_York timezone: 2024-02-02 00:47:31.813949-05:00

Difference in Days:

6. Write a Python program to find the difference in days between two arbitrary dates using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define two arbitrary dates as strings
date_str1 = "2018-03-15"
date_str2 = "2018-04-20"

# Parse the date strings into Pendulum objects
date1 = pendulum.parse(date_str1)
date2 = pendulum.parse(date_str2)

# Calculate the difference in days between the two dates
days_difference = date2.diff(date1).in_days()

# Print the difference in days
print(f"Difference in days between {date_str1} and {date_str2}: {days_difference} days")

Output:

Difference in days between 2018-03-15 and 2018-04-20: 36 days

Add and Subtract Duration:

7. Write a Python program to add 3 hours and 30 minutes to the current date and time, then subtract 1 day using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Add 3 hours and 30 minutes to the current date and time
new_datetime = current_datetime.add(hours=3, minutes=30)

# Subtract 1 day from the new date and time
result_datetime = new_datetime.subtract(days=1)

# Print the result after adding and subtracting
print("Current Date and Time:", current_datetime)
print("After adding 3 hours and 30 minutes:", new_datetime)
print("After subtracting 1 day:", result_datetime)

Output:

Current Date and Time: 2024-02-02 11:22:24.599671+05:30
After adding 3 hours and 30 minutes: 2024-02-02 14:52:24.599671+05:30
After subtracting 1 day: 2024-02-01 14:52:24.599671+05:30

Parsing Date and Time:

8. Write a Python program to parse the string "2019-02-01 15:45:00" into a Pendulum object using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define the date and time string
date_time_str = "2019-02-01 15:45:00"

# Parse the date and time string into a Pendulum object
parsed_datetime = pendulum.parse(date_time_str)

# Print the Pendulum object
print("Parsed Pendulum object:", parsed_datetime)

Output:

Parsed Pendulum object: 2019-02-01 15:45:00+00:00

Human-Readable Difference:

9. Write a Python program to find the human-readable difference between two arbitrary dates (e.g., "2 weeks and 3 days ago") using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define two arbitrary dates as strings
date_str1 = "2019-03-15"
date_str2 = "2019-04-20"

# Parse the date strings into Pendulum objects
date1 = pendulum.parse(date_str1)
date2 = pendulum.parse(date_str2)

# Calculate the difference in a human-readable format
human_readable_difference = date2.diff_for_humans(date1, absolute=True)

# Print the human-readable difference
print(f"Difference between {date_str1} and {date_str2}: {human_readable_difference}")

Output:

Difference between 2019-03-15 and 2019-04-20: 1 month

Check for Leap Year:

10. Write a Python program to determine if the current year is a leap year using Pendulum module.

Code:

# Import the Pendulum module
import pendulum
import calendar

# Get the current year
current_year = pendulum.now().year

# Check if the current year is a leap year
is_leap_year = calendar.isleap(current_year)

# Print the result
if is_leap_year:
    print(f"{current_year} is a leap year.")
else:
    print(f"{current_year} is not a leap year.")

Output:

2024 is a leap year.

First Day of the Month:

11. Write a Python program to print the first day of the current month using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Get the first day of the current month
first_day_of_month = current_datetime.start_of('month')

# Print the first day of the current month
print("First day of the current month:", first_day_of_month)

Output:

First day of the current month: 2024-02-01 00:00:00+05:30

Last Day of the Month:

12. Write a Python program to print the last day of the current month using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Get the last day of the current month
last_day_of_month = current_datetime.end_of('month')

# Print the last day of the current month
print("Last day of the current month:", last_day_of_month)

Output:

Last day of the current month: 2024-02-29 23:59:59.999999+05:30

Week Start and End:

13. Write a Python program to print the start and end dates of the current week using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Get the start date of the current week (Monday)
start_of_week = current_datetime.start_of('week')

# Get the end date of the current week (Sunday)
end_of_week = current_datetime.end_of('week')

# Print the start and end dates of the current week
print("Start date of the current week:", start_of_week)
print("End date of the current week:", end_of_week)

Output:

Start date of the current week: 2024-01-29 00:00:00+05:30
End date of the current week: 2024-02-04 23:59:59.999999+05:30

Is it Weekday or Weekend?:

14. Write a Python program to check if the current day is a weekday or a weekend day using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Get the day of the week (1 for Monday, 2 for Tuesday, ..., 7 for Sunday)
day_of_week = current_datetime.day_of_week

# Check if the current day is a weekday (Monday to Friday)
is_weekday = day_of_week >= 1 and day_of_week <= 5

# Check if the current day is a weekend day (Saturday or Sunday)
is_weekend = day_of_week == 6 or day_of_week == 7

# Print the result
if is_weekday:
    print("Today is a weekday.")
elif is_weekend:
    print("Today is a weekend day.")
else:
    print("Error in day detection.")

Output:

Today is a weekday.

Time Only:

15. Write a Python program to extract and print the time part from the current date and time using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Extract the time part from the current date and time
time_part = current_datetime.format('HH:mm:ss')

# Print the extracted time part
print("Time part from the current date and time:", time_part)

Output:

Time part from the current date and time: 12:24:23 

Interval Intersection:

16. Write a Python program to find the overlapping period from two given two time intervals using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define two time intervals as strings
interval1_start = "2020-03-15T08:00:00"
interval1_end = "2020-03-15T12:00:00"

interval2_start = "2020-03-15T10:30:00"
interval2_end = "2020-03-15T14:00:00"

# Parse the time intervals into Pendulum objects
interval1_start_time = pendulum.parse(interval1_start)
interval1_end_time = pendulum.parse(interval1_end)

interval2_start_time = pendulum.parse(interval2_start)
interval2_end_time = pendulum.parse(interval2_end)

# Find the overlapping period
overlap_start = max(interval1_start_time, interval2_start_time)
overlap_end = min(interval1_end_time, interval2_end_time)

# Check if there is an overlap
if overlap_start <= overlap_end:
    print(f"There is an overlapping period from {overlap_start} to {overlap_end}.")
else:
    print("There is no overlapping period.")

Output:

There is an overlapping period from 2020-03-15 10:30:00+00:00 to 2020-03-15 12:00:00+00:00.

Convert to Timestamp:

17. Write a Python program to convert the current date and time to a Unix timestamp using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Convert the current date and time to a Unix timestamp
unix_timestamp = current_datetime.timestamp()

# Print the Unix timestamp
print("Unix timestamp for the current date and time:", unix_timestamp)

Output:

Unix timestamp for the current date and time: 1706857529.404638

Custom Formatting:

18. Write a Python program to create a custom format for date and time representation and use it for formatting. Use Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Define a custom format for date and time representation
custom_format = "YYYY/MM/DD HH:mm:ss A"

# Format the current date and time using the custom format
formatted_datetime = current_datetime.format(custom_format)

# Print the formatted date and time
print("Formatted date and time using custom format:", formatted_datetime)

Output:

Formatted date and time using custom format: 2024/02/02 12:37:41 PM

Difference in Hours:

19. Write a Python program to find the difference in hours between two arbitrary dates using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define two arbitrary dates as strings
date_str1 = "2019-03-15 10:00:00"
date_str2 = "2019-03-15 14:30:00"

# Parse the date strings into Pendulum objects
date1 = pendulum.parse(date_str1)
date2 = pendulum.parse(date_str2)

# Calculate the difference in hours between the two dates
hours_difference = date2.diff(date1).in_hours()

# Print the difference in hours
print(f"Difference in hours between {date_str1} and {date_str2}: {hours_difference} hours")

Output:

Difference in hours between 2019-03-15 10:00:00 and 2019-03-15 14:30:00: 4 hours

Relative Time:

20. Write a Python program to print the relative time (e.g., "2 hours ago" or "in 30 minutes") for an arbitrary date using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Define an arbitrary date as a string
arbitrary_date_str = "2018-03-15 12:30:00"

# Parse the arbitrary date string into a Pendulum object
arbitrary_date = pendulum.parse(arbitrary_date_str)

# Calculate the relative time
relative_time = arbitrary_date.diff_for_humans()

# Print the relative time
print(f"Relative time for {arbitrary_date_str}: {relative_time}")

Output:

Relative time for 2018-03-15 12:30:00: 6 years ago

Age Calculation:

21. Write a Python program to calculate the person's age from a given birthdate using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Function to calculate age from birthdate
def calculate_age(birthdate):
    # Get the current date
    current_date = pendulum.now()

    # Parse the birthdate string into a Pendulum object
    birthdate = pendulum.parse(birthdate)

    # Calculate the age
    age = current_date.diff(birthdate).in_years()

    return age

# Example birthdate as a string (format: YYYY-MM-DD)
birthdate_str = "1990-05-15"

# Calculate the age using the function
person_age = calculate_age(birthdate_str)

# Print the calculated age
print(f"The person's age with birthdate {birthdate_str} is {person_age} years.")

Output:

The person's age with birthdate 1990-05-15 is 33 years.

Timezone Offset:

22. Write a Python program to find the timezone offset (in hours) for the current timezone using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Get the timezone offset in hours for the current timezone
timezone_offset_hours = current_datetime.offset / 3600

# Print the timezone offset
print(f"Timezone offset for the current timezone: {timezone_offset_hours} hours")

Output:

Timezone offset for the current timezone: 5.5 hours

Number of Days in a Month:

23. Write a Python program to get the number of days from a specific month and year (given) using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Function to get the number of days in a specific month and year
def get_days_in_month(year, month):
    # Create a Pendulum object for the specified month and year
    target_date = pendulum.datetime(year, month, 1)

    # Calculate the number of days in the month
    days_in_month = target_date.days_in_month

    return days_in_month

# Specify the year and month (format: YYYY-MM)
target_year = 2015
target_month = 3

# Get the number of days using the function
days_in_month = get_days_in_month(target_year, target_month)

# Print the result
print(f"The number of days in {pendulum.date(target_year, target_month, 1).format('MMMM YYYY')} is: {days_in_month} days")

Output:

The number of days in March 2015 is: 31 days

Nearest Hour:

24. Write a Python program to round the current time to the nearest hour using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Round the current time to the nearest hour
rounded_datetime = current_datetime.start_of('hour')

# Print the rounded datetime
print("Rounded time to the nearest hour:", rounded_datetime)

Output:

Rounded time to the nearest hour: 2024-02-02 13:00:00+05:30

Time Until Next Weekend:

25. Write a Python program to calculate and print the amount of time until the next Saturday using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Calculate the days remaining until the next Saturday (ISO weekday 6)
days_until_saturday = (6 - current_datetime.weekday()) % 7

# Calculate the next Saturday's date
next_saturday = current_datetime.add(days=days_until_saturday)

# Calculate the time difference until the next Saturday
time_until_saturday = current_datetime.diff(next_saturday)

# Print the amount of time until the next Saturday
print(f"Time until the next Saturday: {time_until_saturday.in_words()}")

Output:

Time until the next Saturday: 2 days

Time Until Midnight:

26. Write a Python program to calculate and print the amount of time until midnight from the current time using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Calculate the time until midnight
time_until_midnight = current_datetime.end_of('day').diff(current_datetime)

# Print the amount of time until midnight
print(f"Time until midnight: {time_until_midnight.in_words()}")

Output:

Time until midnight: 9 hours 15 minutes 54 seconds

Business Days Count:

27. Write a Python program to determine the number of business days between two arbitrary dates (excluding weekends). Use Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Function to calculate business days between two dates
def calculate_business_days(start_date, end_date):
    # Initialize a counter for business days
    business_days = 0

    # Initialize a current date for iteration
    current_date = start_date

    # Loop through each day in the date range
    while current_date <= end_date:
        # Check if the current day is a weekday (Monday to Friday)
        if current_date.weekday() < 5:
            business_days += 1

        # Move to the next day
        current_date = current_date.add(days=1)

    return business_days

# Define two arbitrary dates as strings (format: YYYY-MM-DD)
start_date_str = "2020-12-01"
end_date_str = "2020-12-31"

# Parse the date strings into Pendulum objects
start_date = pendulum.parse(start_date_str)
end_date = pendulum.parse(end_date_str)

# Calculate the business days between the two dates using the function
business_days = calculate_business_days(start_date, end_date)

# Print the result
print(f"Business days between {start_date_str} and {end_date_str}: {business_days} days")

Output:

Business days between 2020-12-01 and 2020-12-31: 23 days

Quarter of the Year:

28. Write a Python program to determine the quarter of the year for the current date. Use Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date
current_date = pendulum.now()

# Determine the quarter of the year
quarter_of_year = (current_date.month - 1) // 3 + 1

# Print the quarter of the year
print(f"Quarter of the year for the current date ({current_date.format('YYYY-MM-DD')}): {quarter_of_year}")

Output:

Quarter of the year for the current date (2024-02-02): 1

Age in Weeks:

29. Write a Python program to calculate the person's age in weeks of a given a birthdate. Use Pendulum module.

Code:

 # Import the Pendulum module
import pendulum

# Function to calculate age in weeks from a given birthdate
def calculate_age_in_weeks(birthdate):
    # Get the current date
    current_date = pendulum.now()

    # Parse the birthdate string into a Pendulum object
    birthdate = pendulum.parse(birthdate)

    # Calculate the age in weeks
    age_in_weeks = current_date.diff(birthdate).in_weeks()

    return age_in_weeks

# Example birthdate as a string (format: YYYY-MM-DD)
birthdate_str = "1990-05-15"

# Calculate the age in weeks using the function
person_age_in_weeks = calculate_age_in_weeks(birthdate_str)

# Print the calculated age in weeks
print(f"The person's age in weeks with birthdate {birthdate_str} is approximately {person_age_in_weeks} weeks.")

Output:

The person's age in weeks with birthdate 1990-05-15 is approximately 1759 weeks.

Time to a Specific Event:

30. Write a Python program to calculate and print the time remaining until that event of a given a future date and time using Pendulum module.

Code:

 # Import the Pendulum module
import pendulum

# Function to calculate and print time remaining until a future event
def time_until_event(event_datetime):
    # Get the current date and time
    current_datetime = pendulum.now()

    # Calculate the time difference until the event
    time_until_event = current_datetime.diff(event_datetime)

    # Print the time remaining until the event
    print(f"Time remaining until the event ({event_datetime.format('YYYY-MM-DD HH:mm:ss')}): {time_until_event.in_words()}")

# Example future date and time as a string (format: YYYY-MM-DD HH:mm:ss)
future_event_str = "2023-12-31 18:00:00"

# Parse the future event string into a Pendulum object
future_event_datetime = pendulum.parse(future_event_str)

# Call the function with the future event datetime
time_until_event(future_event_datetime)

Output:

Time remaining until the event (2023-12-31 18:00:00): 1 month 1 day 15 hours 50 minutes 46 seconds

Set Time to Midnight:

31. Write a Python program to set the time part of the current date to midnight (00:00:00) using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Set the time part of the current date to midnight
midnight_datetime = current_datetime.start_of('day')

# Print the result
print(f"Current datetime: {current_datetime}")
print(f"Date with time set to midnight: {midnight_datetime}")

Output:

Current datetime: 2024-02-02 15:35:07.523211+05:30
Date with time set to midnight: 2024-02-02 00:00:00+05:30

Change Day of the Week:

32. Write a Python program that changes the current day to a different day of the week using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Get the current date and time
current_datetime = pendulum.now()

# Define the desired day of the week (Monday to Sunday: 1 to 7)
desired_day_of_week = 3  # Change this to the desired day (e.g., 3 for Wednesday)

# Calculate the difference in days to the desired day
days_to_desired_day = (desired_day_of_week - current_datetime.day_of_week) % 7

# Change the current date to the desired day
new_datetime = current_datetime.add(days=days_to_desired_day)

# Print the result
print(f"Original datetime: {current_datetime}")
print(f"Datetime with the day changed to {desired_day_of_week}: {new_datetime}")

Output:

Original datetime: 2024-02-02 15:37:26.706953+05:30
Datetime with the day changed to 3: 2024-02-08 15:37:26.706953+05:30

Travel Time:

33. Write a Python program to calculate and print the travel time between two given dates and times them using Pendulum module.

Code:

# Import the Pendulum module
import pendulum

# Function to calculate and print travel time between two dates and times
def calculate_travel_time(start_datetime, end_datetime):
    # Calculate the travel time between two datetimes
    travel_time = start_datetime.diff(end_datetime)

    # Print the travel time
    print(f"Travel time from {start_datetime} to {end_datetime}: {travel_time.in_words()}")

# Example start datetime and end datetime as strings (format: YYYY-MM-DD HH:mm:ss)
start_datetime_str = "2023-06-01 12:30:00"
end_datetime_str = "2023-06-02 15:45:00"

# Parse the datetime strings into Pendulum objects
start_datetime = pendulum.parse(start_datetime_str)
end_datetime = pendulum.parse(end_datetime_str)

# Call the function with the start and end datetimes
calculate_travel_time(start_datetime, end_datetime)

Output:

Travel time from 2023-06-01 12:30:00+00:00 to 2023-06-02 15:45:00+00:00: 1 day 3 hours 15 minutes

Countdown Timer:

34. Write a Python program that creates a countdown timer that prints the remaining time in seconds every second until reaching zero using Pendulum module.

Code:

# Import the Pendulum module
import pendulum
import time

# Function to create and run a countdown timer
def countdown_timer(end_datetime):
    # Get the current date and time
    current_datetime = pendulum.now()

    # Calculate the initial remaining time
    remaining_time = end_datetime.diff(current_datetime)

    # Run the countdown loop
    while remaining_time.total_seconds() > 0:
        # Print the remaining time in seconds
        print(f"Remaining time: {remaining_time.total_seconds()} seconds\n", end='\r')

        # Wait for 1 second
        time.sleep(1)

        # Update the remaining time for the next iteration
        current_datetime = pendulum.now()
        remaining_time = end_datetime.diff(current_datetime)

    # Print a message when the countdown reaches zero
    print("\nCountdown reached zero!")

# Example end datetime as a string (format: YYYY-MM-DD HH:mm:ss)
end_datetime_str = "2023-12-31 23:59:59"

# Parse the end datetime string into a Pendulum object
end_datetime = pendulum.parse(end_datetime_str)

# Call the countdown timer function with the end datetime
countdown_timer(end_datetime)

Output:

Remaining time: 2801659.410176 seconds
Remaining time: 2801660.424509 seconds
Remaining time: 2801661.43167 seconds
Remaining time: 2801662.445267 seconds
Remaining time: 2801663.448513 seconds
Remaining time: 2801664.460863 seconds
Remaining time: 2801665.468188 seconds
Remaining time: 2801666.48114 seconds
Remaining time: 2801667.491533 seconds
Remaining time: 2801668.497517 seconds
Remaining time: 2801669.502577 seconds
Remaining time: 2801670.51506 seconds
Remaining time: 2801671.522194 seconds
.................
.................

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.



Follow us on Facebook and Twitter for latest update.