How to add time in Python datetime

PythonBeginner
Practice Now

Introduction

Python's datetime module is a powerful tool for working with dates and times. This tutorial will guide you through various methods of adding time to datetime objects, helping you perform accurate and flexible time calculations in Python. You will learn how to use timedelta for simple additions and explore practical examples of time manipulation.

Understanding Python Datetime

Before adding time, it is important to understand the fundamental components of the datetime module.

Core Datetime Components

The datetime module provides several key classes:

Class Description
date Represents a date (year, month, day)
time Represents a time (hour, minute, second)
datetime Combines date and time
timedelta Represents a duration of time

Creating Datetime Objects

You can create datetime objects in several ways. Let's create a simple Python script to see how.

Open the integrated terminal in the WebIDE and navigate to the project directory if you are not already there.

cd ~/project

Create a new file named datetime_basics.py in the ~/project directory using the WebIDE file explorer or the command line.

touch datetime_basics.py

Open datetime_basics.py in the WebIDE editor and add the following code:

from datetime import date, time, datetime

## Creating a date object
current_date = date.today()
print(f"Current date: {current_date}")

## Creating a time object (from current datetime)
current_time = datetime.now().time()
print(f"Current time: {current_time}")

## Creating a datetime object
current_datetime = datetime.now()
print(f"Current datetime: {current_datetime}")

## Creating a specific datetime object
specific_datetime = datetime(2023, 6, 15, 14, 30, 45)
print(f"Specific datetime: {specific_datetime}")

Save the file. Now, run the script from the terminal:

python datetime_basics.py

You will see output similar to this:

Current date: YYYY-MM-DD
Current time: HH:MM:SS.microseconds
Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Specific datetime: 2023-06-15 14:30:45

This shows how to create basic date, time, and datetime objects.

Key Datetime Attributes

datetime objects have attributes like year, month, day, hour, minute, and second that you can access.

Let's add to our datetime_basics.py script to demonstrate accessing these attributes.

Open datetime_basics.py again and add the following lines at the end:

print(f"Year: {specific_datetime.year}")
print(f"Month: {specific_datetime.month}")
print(f"Day: {specific_datetime.day}")
print(f"Hour: {specific_datetime.hour}")
print(f"Minute: {specific_datetime.minute}")
print(f"Second: {specific_datetime.second}")

Save the file and run it again:

python datetime_basics.py

The output will now include the individual components of the specific_datetime:

Current date: YYYY-MM-DD
Current time: HH:MM:SS.microseconds
Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Specific datetime: 2023-06-15 14:30:45
Year: 2023
Month: 6
Day: 15
Hour: 14
Minute: 30
Second: 45

Understanding these fundamentals is the first step to performing time additions.

Adding Time with timedelta

The most common way to add time to a datetime object in Python is by using the timedelta class. A timedelta object represents a duration.

Creating timedelta Objects

You can create timedelta objects using various time units like days, hours, minutes, seconds, milliseconds, and microseconds.

Let's create a new Python script to explore timedelta.

Create a new file named time_addition.py in the ~/project directory.

touch time_addition.py

Open time_addition.py and add the following code:

from datetime import datetime, timedelta

## Get the current datetime
current_datetime = datetime.now()
print(f"Current datetime: {current_datetime}")

## Create a timedelta of 5 days
five_days = timedelta(days=5)
print(f"Timedelta of 5 days: {five_days}")

## Create a timedelta of 3 hours and 30 minutes
three_hours_thirty_minutes = timedelta(hours=3, minutes=30)
print(f"Timedelta of 3 hours 30 minutes: {three_hours_thirty_minutes}")

## Create a timedelta of 1 week and 2 days
one_week_two_days = timedelta(weeks=1, days=2)
print(f"Timedelta of 1 week 2 days: {one_week_two_days}")

Save the file and run it:

python time_addition.py

The output will show the current datetime and the created timedelta objects:

Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Timedelta of 5 days: 5 days, 0:00:00
Timedelta of 3 hours 30 minutes: 3:30:00
Timedelta of 1 week 2 days: 9 days, 0:00:00

Notice that timedelta(weeks=1, days=2) is represented as 9 days. timedelta normalizes the duration into days, seconds, and microseconds.

Adding timedelta to datetime

You can add a timedelta object to a datetime object to get a new datetime object representing a future point in time.

Let's add code to time_addition.py to perform time addition.

Open time_addition.py and add the following lines at the end:

## Add 5 days to the current datetime
future_datetime_days = current_datetime + five_days
print(f"Datetime after adding 5 days: {future_datetime_days}")

## Add 3 hours and 30 minutes to the current datetime
future_datetime_hours_minutes = current_datetime + three_hours_thirty_minutes
print(f"Datetime after adding 3 hours 30 minutes: {future_datetime_hours_minutes}")

## Add 1 week and 2 days to the current datetime
future_datetime_weeks_days = current_datetime + one_week_two_days
print(f"Datetime after adding 1 week 2 days: {future_datetime_weeks_days}")

Save the file and run it:

python time_addition.py

The output will now show the original datetime and the resulting datetimes after adding the timedelta objects:

Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Timedelta of 5 days: 5 days, 0:00:00
Timedelta of 3 hours 30 minutes: 3:30:00
Timedelta of 1 week 2 days: 9 days, 0:00:00
Datetime after adding 5 days: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 3 hours 30 minutes: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 1 week 2 days: YYYY-MM-DD HH:MM:SS.microseconds

The output shows the new datetime values after the additions. This demonstrates the basic usage of timedelta for adding time.

Practical Time Calculations

timedelta is very useful for practical time calculations, such as finding a date in the future or calculating the duration between two points in time.

Calculating Future Dates

You can easily calculate a date a certain number of days, weeks, or even years in the future (by converting years to days).

Let's add a function to time_addition.py to calculate a future date.

Open time_addition.py and add the following function definition and usage at the end:

def get_future_date(start_date, days_to_add):
    """Calculates a future date by adding a number of days."""
    future_date = start_date + timedelta(days=days_to_add)
    return future_date

## Example: Find the date 30 days from now
thirty_days_from_now = get_future_date(datetime.now(), 30)
print(f"Date 30 days from now: {thirty_days_from_now}")

Save the file and run it:

python time_addition.py

The output will now include the date 30 days from the current date:

Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Timedelta of 5 days: 5 days, 0:00:00
Timedelta of 3 hours 30 minutes: 3:30:00
Timedelta of 1 week 2 days: 9 days, 0:00:00
Datetime after adding 5 days: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 3 hours 30 minutes: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 1 week 2 days: YYYY-MM-DD HH:MM:SS.microseconds
Date 30 days from now: YYYY-MM-DD HH:MM:SS.microseconds

Calculating Time Differences

You can also subtract one datetime object from another to get a timedelta object representing the duration between them.

Let's add code to time_addition.py to calculate the difference between two dates.

Open time_addition.py and add the following code at the end:

## Calculate the difference between two specific datetimes
date1 = datetime(2023, 1, 1)
date2 = datetime(2023, 12, 31)

time_difference = date2 - date1
print(f"Difference between {date1} and {date2}: {time_difference}")

## Access components of the timedelta difference
print(f"Days difference: {time_difference.days}")
print(f"Total seconds difference: {time_difference.total_seconds()}")

Save the file and run it:

python time_addition.py

The output will show the difference between the two dates:

Current datetime: YYYY-MM-DD HH:MM:SS.microseconds
Timedelta of 5 days: 5 days, 0:00:00
Timedelta of 3 hours 30 minutes: 3:30:00
Timedelta of 1 week 2 days: 9 days, 0:00:00
Datetime after adding 5 days: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 3 hours 30 minutes: YYYY-MM-DD HH:MM:SS.microseconds
Datetime after adding 1 week 2 days: YYYY-MM-DD HH:MM:SS.microseconds
Date 30 days from now: YYYY-MM-DD HH:MM:SS.microseconds
Difference between 2023-01-01 00:00:00 and 2023-12-31 00:00:00: 364 days, 0:00:00
Days difference: 364
Total seconds difference: 31449600.0

This demonstrates how timedelta is used for both adding time and calculating the duration between two points in time. These are fundamental operations for many time-based applications.

Summary

In this lab, you have learned the fundamentals of Python's datetime module, including creating date, time, and datetime objects. You explored how to use the timedelta class to represent durations and how to add timedelta objects to datetime objects to perform time additions. You also practiced practical time calculations, such as finding future dates and calculating the difference between two datetimes. These skills are essential for handling time-based operations in your Python programs.