Python Datetime

Simplify and streamline your code by leveraging the powerful Python datetime module for all your date, time, and timezone manipulation needs. Effortlessly perform calculations on dates and times, format dates to meet your specific requirements, manage time zone differences for international projects, and schedule tasks with precision

Python-Datetime
Table of Contents

What is Datetime in Python?

Python’s datetime module is your toolbox for working with dates and times. It lets you represent specific dates and times, perform calculations like finding the difference between two dates, and format dates in a way that reads easily for you or others.

Python Datetime Syntax

date_object = datetime.date(year, month, day)

  • year: Required integer value representing the year (e.g., 2024).
  • month: Required integer value between 1 and 12 for the month.
  • day: Required integer value between 1 and 31 for the day of the month.

Importing the Datetime Module

To use the dates and times in your Python code, you’ll need to import the datetime module.

import datetime

Once you import datetime, you can use the various functions and classes it provides within your code.

Python Datetime Example

# Import the datetime module
import datetime

# Get today's date
today = datetime.date.today()

# Print today's date in a user-friendly format (optional formatting)
print(f"Today's date is: {today}")  # Prints YYYY-MM-DD
print(f"Another format: {today.strftime('%B %d, %Y')}")  # Custom formatting

Explanation

  • Line 2: Imports the datetime module for use in our code.
  • Line 5: Creates a date object using datetime.date.today() which represents the current date.
  • Line 8: Prints today’s date in the default format (YYYY-MM-DD).
  • Line 9: Demonstrates optional formatting using the strftime method. Here, '%B' formats the month as a full name (e.g., March), '%d' formats the day as zero-padded (01-31), and '%Y' formats the year.

Output

Today’s date is: 2024-04-10
Another format: April 10, 2024


Essential Features of the Python Datetime Module

Python datetime module offers rich features for working with dates and times. Here are some key highlights:

Creating objects

Build date, time, and datetime objects using datetime.date(), datetime.time(), and datetime.datetime() for specific dates and times.

Time Differences

Calculate the time difference between two dates or times using datetime.timedelta.
timedelta_object = end_datetime - start_datetime

Formatting

Easily format dates and times for human readability with the strftime method. You can customize the output format using codes like '%Y' for year, '%B' for full month name, and '%d' for day.

Time Zones

Handle time zone information with the timezone module (not built-in in all Python versions).

Example

# Import required modules
import datetime

# Create a datetime object for today
today = datetime.datetime.today()

# Calculate time difference in one week (7 days)
one_week_delta = datetime.timedelta(days=7)
future_date = today + one_week_delta  # Add the time difference

# Format both dates for readability
today_formatted = today.strftime("%Y-%m-%d (%A)")  # YYYY-MM-DD (Weekday)
future_formatted = future_date.strftime("%B %d, %Y")  # Month Day, YYYY

# Print the formatted dates
print(f"Today: {today_formatted}")
print(f"One week from today: {future_formatted}")

Explanation

  • Lines 2-5: Import datetime for creating date/time objects.
  • Line 5: Creates a datetime object representing the current date and time.
  • Lines 8-9: Creates a timedelta object representing one week (7 days) and adds it to today to get a future date.
  • Lines 12-13: Format today and the future date using strftime with custom formats for better readability.
  • Lines 16-17: Print the formatted dates.

Output

Today: 2024-04-10 (Wednesday)
One week from today: April 17, 2024


Customizing Date and Time Formatting with strftime()

In Python, the strftime() method is your tool for formatting datetime objects into human-readable strings. 

Syntax

formatted_string = datetime_object.strftime(format_code)

  • datetime_object: The datetime object you want to represent as a string.
  • format_code: String containing format placeholders that define the output format.

Example

# Import the datetime module
import datetime

# Get the current datetime
now = datetime.datetime.now()

# Format the datetime object (YYYY-MM-DD)
formatted_date = now.strftime("%Y-%m-%d")

# Print the formatted date string
print(f"Today's date: {formatted_date}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a datetime object using datetime.datetime.now() to capture the current date and time.
  • Line 8: Formats the now object using the strftime("%Y-%m-%d") code. This creates a string with the year, month, and day separated by hyphens.
  • Line 11: Prints the formatted formatted_date string.

Output

Today’s date: 2024-04-10


Understanding Datetime Format Codes

In Python, format codes are special symbols used within the strftime() method to control the layout of your formatted date and time strings. They act like placeholders that tell Python which pieces of your datetime object you want to include and how to display them. Here’s a breakdown of common categories:

Date Components

  • %Y: Year with century (e.g., 2024)
  • %m: Zero-padded month (01-12)
  • %d: Zero-padded day of the month (01-31)
  • %B: Full month name (e.g., January)
  • %A: Full weekday name (e.g., Tuesday)

Time Components

  • %H: Hour (24-hour format, 00-23)
  • %M: Minute (00-59)
  • %S: Second (00-59)
  • %f: Microsecond (000000-999999)

Time Zone Information

  • %z: UTC offset (e.g., +0100, -0700)
  • %Z: Time zone name (may not be available on all systems)

Other Components

  • %%: A literal ‘%‘ character

Example

import datetime

now = datetime.datetime.now()

# Format 1: YYYY-MM-DD HH:MM (24-hour clock)
formatted_1 = now.strftime("%Y-%m-%d %H:%M")

# Format 2: Full weekday, Month Day, Year - Time (12-hour clock) 
formatted_2 = now.strftime("%A, %B %d, %Y - %I:%M %p")  # %p gives AM/PM 

print(formatted_1) 
print(formatted_2)

Explanation

  • Line 1: Import the datetime module.
  • Line 3: Get the current datetime with datetime.datetime.now().
  • Line 6-9: Format the datetime using two different styles.
  • Line 11-12: Print the formatted strings. Notice the use of format codes like %d for the day, %B for the full month name, and %I for the hour in a 12-hour format.

Output

2024-04-10 21:10
Wednesday, April 10, 2024 – 09:10 PM


Working with Datetime Objects

Datetime objects in Python’s datetime module are like labels for specific dates and times. They store the exact date and time information, allowing you to perform calculations, comparisons, and formatting. Here’s how to create a datetime object:

Syntax

datetime_object = datetime.datetime(year, month, day, [hour, minute, second, microsecond])

  • year: Required integer value representing the year (e.g., 2024).
  • month: Required integer value between 1 and 12 for the month.
  • day: Required integer value between 1 and 31 for the day of the month.
  • hour (optional): Integer value for hour (0-23).
  • minute (optional): Integer value for minute (0-59).
  • second (optional): Integer value for second (0-59).
  • microsecond (optional): Integer microsecond value (0-999999). By default, microseconds are set to 0.

Example

# Import the datetime module
import datetime

# Get today's date and time
today_datetime = datetime.datetime.today()

# Create a datetime object for a specific time (replace with your desired time)
specific_datetime = datetime.datetime(2023, 12, 25, 15, 0, 0)  # Dec 25th 2023, 3PM

# Print both datetime objects
print(f"Today: {today_datetime}")
print(f"Specific time: {specific_datetime}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a datetime object representing the current date and time using datetime.datetime.today().
  • Line 8: Creates a datetime object for a specific date and time (replace with your desired values).
  • Line 8-12: Prints both the today_datetime and the specific_datetime objects.

Output

Today: 2024-04-10 21:12:15.906440
Specific time: 2023-12-25 15:00:00


Getting the Current Date and Time with datetime.today()

In Python’s datetime module, the datetime.today() function is a handy shortcut for the current date and time. It captures the exact moment your code is running.

Syntax

current_datetime = datetime.today()

This single line retrieves the current date, including the time, and stores it in a datetime object.

Example

# Import the datetime module
import datetime

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

# Print the current date and time
print(f"The current date and time is: {now}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Assigns the current date and time retrieved by datetime.today() to the variable now.
  • Line 8: Prints the current date and time stored in the now variable using an f-string for easy formatting.

Output

The current date and time is: 2024-04-10 21:16:33.137534


Comparing Python Datetime Objects

Python provides a straightforward way to compare two datetime objects to see if one is earlier, later, or equal to the other. You can use comparison operators like < (less than), > (greater than), == (equal to), and so on. These operators work directly with datetime objects.

Example

import datetime

# Create two datetime objects
datetime_1 = datetime.datetime(2024, 3, 15, 10, 30)
datetime_2 = datetime.datetime(2024, 3, 14, 12, 15)

# Compare the datetime objects
is_datetime_1_newer = datetime_1 > datetime_2  # True

# Print the comparison result
print(f"Datetime 1 is newer than Datetime 2: {is_datetime_1_newer}")

Explanation

  • Lines 4-5: Create two datetime objects with different dates and times using datetime.datetime(year, month, day, hour, minute).
  • Line 8: Compares datetime_1 and datetime_2 using the > operator. This returns True because datetime_1 is chronologically later.
  • Line 11: Prints the result of the comparison.

Output

Datetime 1 is newer than Datetime 2: True


The Python Date Class

Python’s date class (part of the datetime module) is designed to represent dates (year, month, and day) without the time component. Think of it as a calendar portion of a datetime object. You can use it to store specific dates (like a holiday, birthday, or historical event), and it’s helpful for calculations or comparisons involving only the date portion.

Creating Date Objects with datetime.date()

To create a date object in Python that represents just the year, month, and day, you use datetime.date() function.

Syntax

date_object = datetime.date(year, month, day)

  • year: Required integer value representing the year (e.g., 2024).
  • month: Required integer value between 1 and 12 for the month.
  • day: Required integer value between 1 and 31 for the day of the month.

Example

# Import the datetime module
import datetime

# Create a date object for next year's New Year's Day
new_years_day = datetime.date(2025, 1, 1)

# Print the date 
print(f"Next year's New Year's Day is: {new_years_day}")

Explanation

  • Line 2: Imports the datetime module for use in our code.
  • Line 5: Creates a date object using datetime.date(2025, 1, 1) representing 2025-01-01 (January 1st, 2025).
  • Line 8: Prints the created date object in a formatted way.

Output

Datetime 1 is newer than Datetime 2: True

Retrieving the Current Date with date.today()

The date.today() function in Python’s datetime module gives you a convenient way to get the current date. It returns a date object representing today’s date on your system’s calendar.

Syntax

todays_date = datetime.date.today()

Example

# Import the datetime module
import datetime

# Get today's date using datetime.date.today()
today = datetime.date.today()

# Print the date 
print(f"Today's date is: {today}")

Explanation

  • Line 2: Imports the datetime module for use in our code.
  • Line 5: Calls the datetime.date.today() function and assigns the resulting date object to the variable today.
  • Line 8: Prints today’s date in a formatted way.

Output

Today’s date is: 2024-04-10

Constructing Dates from Timestamps

Extracting a date from a timestamp in Python requires converting the timestamp value into a datetime object. Timestamps are often represented in seconds since a specific point in time (like January 1, 1970). Here’s how to do it:

from_timestamp(timestamp) 

This function might be from an external library, depending on the format of your timestamp.

timestamp: Required numerical value representing the timestamp (often in seconds).

Example

# Import the datetime module
import datetime

# Sample timestamp (assuming seconds since epoch)
timestamp = 1678821200  # Replace with your timestamp value

# Convert timestamp to datetime object (assuming epoch in seconds)
date_from_timestamp = datetime.datetime.fromtimestamp(timestamp)

# Extract and print the date part
date_object = date_from_timestamp.date()
print(f"Extracted date: {date_object}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: This line defines a sample timestamp (1678821200, which corresponds to September 13, 2023 12:00 PM UTC). Replace this with your actual timestamp value.
  • Line 8: Converts the timestamp (timestamp) into a datetime object using datetime.datetime.fromtimestamp(). Note that this assumes your timestamp is in seconds since epoch (January 1, 1970). If your timestamp format differs, you might need a library specific to handle that format.
  • Line 11: Extracts the date part from the datetime object using the .date() method and assigns it to date_object.
  • Line 12: Prints the extracted date in a user-friendly format.

Output

Extracted date: 2023-03-14

Extracting Date Components (Year, Month, Day)

Here’s how to print today’s year, month, and day in Python:

  1. Import datetime module
  2. Get today’s date
  3. Extract components
  4. Print the values

Example

# Import the datetime module
import datetime

# Get today's date
today = datetime.date.today()

# Extract year, month, day
year = today.year
month = today.month
day = today.day

# Print year, month, and day (f-string for easy formatting)
print(f"Today's date: {year}, {month}, {day}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Calls datetime.date.today() and assigns the resulting date object (representing today’s date) to the variable today.
  • Lines 8-10: Extracts the year, month, and day components from the today object using the .year, .month, and .day attributes, respectively.
  • Line 13: Uses an f-string to print the extracted year, month, and day in a user-friendly format. You can modify this line for different formatting styles (e.g., “YYYY-MM-DD”).

Output

Today’s date: 2024, 4, 10

Formatting Dates as Strings

In Python, you can transform a datetime object into a human-readable string format using the strftime method. This method offers a flexible way to customize how the date is displayed.

Syntax

formatted_date_string = date_object.strftime(format_code)

  • date_object: This is the datetime object you want to convert to a string.
  • format_code: This is a string that defines the output format. Common codes include:
    • %Y: Year (e.g., 2024)
    • %m: Month as a zero-padded number (01-12)
    • %d: Day of the month as a zero-padded number (01-31)
    • %B: Full month name (e.g., January)
    • %A: Full weekday name (e.g., Thursday)

Example

# Import the datetime module
import datetime

# Create a date object
today = datetime.date.today()

# Format the date object (YYYY-MM-DD)
formatted_date = today.strftime("%Y-%m-%d")

# Print the formatted date
print(f"Today's date in YYYY-MM-DD format: {formatted_date}")

# Optional: Format with full month name
print(f"Today with full month: {today.strftime('%A, %B %d, %Y')}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a date object for today using datetime.date.today().
  • Line 8: Formats the today object using strftime("%Y-%m-%d"). This code creates a string with the year, month, and day separated by hyphens.
  • Line 11: Prints the formatted date string.
  • Line 14: (Optional) Demonstrates formatting with different codes. Here, '%A' gives the full weekday name, '%B' gives the full month name and ', ' adds commas and spaces for readability.

Output

Today’s date in YYYY-MM-DD format: 2024-04-10
Today with full month: Wednesday, April 10, 2024


The Python Time Class

The time class within Python’s datetime module represents time (hour, minute, second, microsecond). Think of it like the clock portion of a datetime object. You can use the time class to represent a specific time of day (e.g., lunch break at 12:30 PM) and perform time-related calculations and comparisons. To create a time object, you use datetime.time(hour, minute, second, microsecond).

Creating Time Objects with datetime.time()

To create a time object in Python that represents just the hour, minute, second (and optionally microseconds), you can use the datetime.time() function.

Syntax

time_object = datetime.time(hour, minute, second, microsecond=0)

  • hour: This is a required integer value between 0 and 23 (represents hour in a 24-hour clock).
  • minute: This is a required integer value between 0 and 59.
  • second (optional): Integer value between 0 and 59. Defaults to 0.
  • microsecond (optional): Integer value between 0 and 999999. Defaults to 0.

Example

# Import the datetime module
import datetime

# Create a time object for a specific time (replace if needed)
meeting_time = datetime.time(10, 30, 0)  # 10:30 AM

# Print the time object
print(f"Meeting time: {meeting_time}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a time object using datetime.time(10, 30, 0), representing 10:30 AM (hour 10, minute 30, second 0).
  • Line 8: Prints the created time object in a default format.

Output

Meeting time: 10:30:00

Retrieving the Current Time

Finding the current time in Python is straightforward using the datetime module. Here’s how to do it:

  1. Import datetime
  2. Get current datetime
  3. Extract time component

Example

# Import the datetime module
import datetime

# Get the current datetime
now = datetime.datetime.now()

# Extract and print the current time
current_time = now.time()
print(f"The current time is: {current_time}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Calls datetime.datetime.now() and assigns the resulting datetime object (including date and time) to the variable now.
  • Line 8: Extracts the time portion from the now object using the .time() method and stores it in current_time.
  • Line 9: Prints the extracted current_time object, which represents the current time.

Output

The current time is: 21:26:15.181412

Extracting Time Components (Hour, Minute, Second, Microsecond)

To extract and print the individual components of a time object (hour, minute, second, microsecond) in Python, you can leverage the attributes of the time class. Here’s how:

  • time_object.hour: Attribute holds the hour value (0-23).
  • time_object.minute: Attribute holds the minute value (0-59).
  • time_object.second: Attribute holds the second value (0-59).
  • time_object.microsecond: Attribute holds the microsecond value (0-999999).

Example

# Import the datetime module
import datetime

# Create a time object (replace with desired time if needed)
specific_time = datetime.time(15, 43, 22, 123456)

# Extract hour, minute, second, and microsecond
hour = specific_time.hour
minute = specific_time.minute
second = specific_time.second
microsecond = specific_time.microsecond

# Print the extracted components
print(f"Hour: {hour}, Minute: {minute}, Second: {second}, Microsecond: {microsecond}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a time object with specific values using datetime.time(hour, minute, second, microsecond).
  • Lines 8-11: Extracts the hour, minute, second, and microsecond components from the specific_time object using the corresponding attributes (.hour, .minute, .second, and .microsecond).
  • Line 14: Prints the extracted values in a user-friendly format.

Output

Hour: 15, Minute: 43, Second: 22, Microsecond: 123456

Formatting Time as Strings

Like with dates, you can convert a time object in Python into a readable string format using the strftime method. This method provides control over how the time is displayed. Here’s the syntax for strftime with a time object:

Syntax

formatted_time_string = time_object.strftime(format_code)

  • time_object: This is the time object you want to represent as a string.
  • format_code: This is a string that defines the output format. Common codes include:
    • %H: Hour in 24-hour format (00-23).
    • %M: Minute (00-59).
    • %S: Second (00-59).
    • %f: Microsecond (000000-999999).

Example

# Import the datetime module
import datetime

# Create a time object
specific_time = datetime.time(17, 10, 5)

# Format the time object (HH:MM:SS)
formatted_time = specific_time.strftime("%H:%M:%S")

# Print the formatted time string
print(f"Formatted time: {formatted_time}")

# Optional: Format with microseconds (HH:MM:SS.ffffff)
print(f"Including microseconds: {specific_time.strftime('%H:%M:%S.%f')}")

Explanation

  • Line 2: Imports the datetime module.
  • Line 5: Creates a time object for a specific time using datetime.time(hour, minute, second).
  • Line 8: Formats the specific_time object using strftime("%H:%M:%S"), resulting in a string with hours, minutes, and seconds separated by colons.
  • Line 11: Prints the formatted time string.
  • Line 14: (Optional) Demonstrates including microseconds using the %f format code.

Output

Formatted time: 17:10:05
Including microseconds: 17:10:05.000000


Converting Strings to Datetime Objects

In Python, you can transform a string representing a date and time into a datetime object. Here’s a breakdown of two common methods:

Using the strptime() Method

Python’s datetime.strptime() method translates date/time strings into datetime objects. You provide the string and a format code describing its structure (e.g., month format). The code then converts the string into a datetime object.

Syntax

datetime_object = datetime.datetime.strptime(date_string, format_code)

  • date_string: This is the string containing your date and time information.
  • format_code: This string specifies the exact format of your date_string using the same format codes as in strftime (e.g., “%Y-%m-%d” for ‘2023-12-25’).

Utilizing the fromisoformat() Method

The fromisoformat() method in Python simplifies converting ISO 8601 formatted strings (e.g., ‘YYYY-MM-DDTHH:MM:SS’) directly into datetime objects. It understands this specific format without needing extra format codes like strptime().

Syntax

datetime_object = datetime.datetime.fromisoformat(date_string)

date_string: A string representing the date and time in the ISO 8601 format (e.g., “2023-12-25T14:30:00”).

Note: this method is not as flexible for custom formats as strptime.

Example

import datetime

# Example date string
date_string = "2023-12-25"
date_string_iso = "2023-12-25T14:30:59" 

# Convert using strptime() method:
datetime_strptime = datetime.datetime.strptime(date_string, "%Y-%m-%d")

# Convert using fromisoformat() method
datetime_fromiso = datetime.datetime.fromisoformat(date_string_iso)

print(datetime_strptime)
print(datetime_fromiso)

Explanation

  • Line 1: Import the datetime module.
  • Lines 4-5: Define a regular date string and one in the ISO 8601 format.
  • Line 8: Convert date_string using strptime with a matching format code.
  • Line 11: Convert date_string_iso using fromisoformat.
  • Lines 13-14: Print the resulting datetime objects.

Output

2023-12-25 00:00:00
2023-12-25 14:30:59


The Python Timedelta Class: Representing Time Durations

The timedelta class in Python helps you represent and work with durations between dates or times. It’s like a measuring tape for time, but it measures in days, hours, minutes, seconds, and even microseconds instead of inches or centimeters. Here’s the syntax for creating a timedelta object:

Syntax

timedelta(weeks=w, days=d, hours=h, minutes=m, seconds=s, microseconds=ms)

  • To define the duration, you can specify any combination of these arguments (weeks, days, hours, minutes, seconds, microseconds).
  • By default, all arguments are optional and set to 0.

Example

from datetime import timedelta, datetime

# Create a timedelta object (2 days, 3 hours)
time_delta = timedelta(days=2, hours=3)

# Add the timedelta to a datetime object
today = datetime.today()
new_date = today + time_delta

# Print the new date (2 days and 3 hours from today)
print(f"New date: {new_date}")

Explanation

  • Line 4: Imports timedelta from the datetime module.
  • Line 7: Creates a timedelta object with 2 days and 3 hours using timedelta(days=2, hours=3).
  • Line 8: Gets the current date and time using datetime.datetime.today(). Then, it adds the time_delta object to today using the + operator.
  • Line 11: Prints the new_date, which is 2 days and 3 hours from the current date and time.

Output

New date: 2024-04-13 00:30:55.298783

Key Operations with Timedelta Objects

The timedelta class in Python offers various operations to manipulate durations. Here are some common ones:

Addition and Subtraction: You can add or subtract timedelta objects from datetime objects or other timedelta objects.

  • new_datetime = datetime_object + timedelta(days=x) (add days)
  • time_delta_2 = time_delta_1 – timedelta(hours=y) (subtract hours)

Multiplication and Division: You can multiply a timedelta object by a number to scale the duration. Division by a number results in a float representing the number of times the scaled duration fits within the original duration.

  • scaled_delta = time_delta * 2 (double the duration)
  • days_passed = target_date / time_delta (calculate days between dates)

Example

from datetime import datetime, timedelta

# Create timedelta objects
delta_1 = timedelta(days=2, hours=5)
delta_2 = timedelta(hours=3)

# Add timedelta objects
combined_delta = delta_1 + delta_2  # timedelta(days=2, hours=8)

# Subtract timedelta objects
remaining_time = delta_1 - delta_2  # timedelta(days=2, hours=2)

# Multiply a timedelta by a number
double_delta = delta_1 * 2  # timedelta(days=4, hours=10)

# Calculate days between dates (division by timedelta results in float)
target_date = datetime(2024, 3, 18)
days_passed = (target_date - datetime.today()) / delta_1  # approximate days between today and target date

# Print the results
print(f"Combined duration: {combined_delta}")
print(f"Remaining time: {remaining_time}")
print(f"Doubled duration: {double_delta}")
print(f"Estimated days until target date: {days_passed:.2f}")  # format to show 2 decimal places

Explanation

  • Lines 4-5: Import necessary modules and create timedelta objects.
  • Lines 8-11: Demonstrate addition and subtraction of timedelta objects.
  • Line 14: Multiply a timedelta by a number.
  • Lines 18-21: Calculate the approximate days between two dates by dividing the difference between the dates (target_date minus today’s date) by delta_1.
  • Lines 22-24: Print the results of each operation. Notice how division by timedelta results in a float representing the number of times the scaled duration fits within the original duration. We format the days passed to show two decimal places.

Output

Combined duration: 2 days, 8:00:00
Remaining time: 2 days, 2:00:00
Doubled duration: 4 days, 10:00:00
Estimated days until target date: -10.82

Calculating Differences Between Timedeltas

Finding the difference between two timedelta objects in Python is straightforward. You can subtract them. 

Syntax

result_timedelta = timedelta_1 – timedelta_2

  • timedelta_1: First timedelta object.
  • timedelta_2: Second timedelta object you want to subtract.

The resulting timedelta object represents the duration between timedelta_1 and timedelta_2. A positive result indicates timedelta_1 lasted longer than timedelta_2, and vice versa for a negative result.

Example

from datetime import timedelta

# Create timedelta objects
time_delta_1 = timedelta(days=3, hours=2)
time_delta_2 = timedelta(days=1, hours=5)

# Find the difference between the timedelta objects
difference = time_delta_1 - time_delta_2

# Print the result (represents the duration between timedelta_1 and timedelta_2)
print(f"The difference between the timedeltas: {difference}")

Explanation

  • Lines 4-5: Import timedelta and create two timedelta objects with different durations.
  • Line 8: Subtract time_delta_2 from time_delta_1 using the operator. This stores the difference in the difference variable.
  • Line 11: Print the difference, which represents the duration between the two original timedelta objects.

Output

The difference between the timedeltas: 1 day, 21:00:00

Adding and Subtracting Days from Dates

Adding days to a datetime object in Python is straightforward. You can use the timedelta class to create a duration and add it to your datetime object. 

Syntax

new_datetime = datetime_object + timedelta(days=number_of_days)

  • datetime_object: This is the datetime object you want to modify.
  • timedelta(days=number_of_days): This creates a timedelta object representing the number of days you want to add (positive integer for future dates, negative for past dates).

Example

from datetime import datetime, timedelta

# Create a datetime object
base_date = datetime(year=2024, month=3, day=14)

# Number of days to add (change as needed)
days_to_add = 5

# Create a timedelta object with the desired number of days
time_delta = timedelta(days=days_to_add)

# Add the timedelta to the datetime object to get the new date
new_date = base_date + time_delta

# Print the original and new dates
print(f"Original date: {base_date}")
print(f"New date ({days_to_add} days later): {new_date}")

Explanation

  • Lines 4-7: Import datetime and timedelta from the datetime module. Create a datetime object (base_date) with a specific date.
  • Line 10: Define the number of days to add (days_to_add) and create a timedelta object with that value.
  • Line 13: Add the time_delta to the base_date using the + operator. This creates a new datetime object (new_date) with the specified number of days added.
  • Lines 16-17: Print the original and new dates with the added days.

Output

Original date: 2024-03-14 00:00:00
New date (5 days later): 2024-03-19 00:00:00

Measuring Durations

The timedelta class has a handy method called total_seconds(). You call this method on your timedelta object to get the total number of seconds it represents.

Syntax

total_seconds = timedelta_object.total_seconds()

timedelta_object: This is the timedelta object you want to convert to seconds.

Example

from datetime import timedelta

# Create a timedelta object (change values as needed)
time_delta = timedelta(days=2, hours=1, minutes=30, seconds=15)

# Get the total number of seconds from the timedelta object
total_seconds = time_delta.total_seconds()

# Print the total seconds
print(f"The total number of seconds: {total_seconds}")

Explanation

  • Line 4: Import timedelta and create a timedelta object with a specific duration.
  • Line 7: Call the total_seconds() method on time_delta to get the total number of seconds it contains.
  • Line 10: Print the total_seconds value.

Output

The total number of seconds: 178215.0