Skip to main content

Introduction to Python Datetime

Python Datetime

The datetime module provides classes and functions for working with dates, times, and time intervals.

It allows you to manipulate and format dates and times, perform calculations, and extract information from them.

Here's an overview of how to work with dates and times using the datetime module:

Importing the datetime Module

Before using the datetime module, you need to import it.

import datetime

Date Creation

The datetime module provides the date class for working with dates. You can create a date object using the date() constructor, specifying the year, month, and day.

# Create a date object for March 15, 2022
my_date = datetime.date(2022, 3, 15)

You can also create date objects for the current date using the today() method:

# Create a date object for the current date
today = datetime.date.today()

Time Creation

The datetime module provides the time class for working with times.

You can create a time object using the time() constructor, specifying the hour, minute, second, and microsecond.

# Create a time object for 9:30:45 AM
my_time = datetime.time(9, 30, 45)

You can also create time objects for the current time using the now() method:

# Create a time object for the current time
current_time = datetime.datetime.now().time()

Datetime Creation

The datetime module provides the datetime class for working with both dates and times.

You can create a datetime object using the datetime() constructor, specifying the year, month, day, hour, minute, second, and microsecond.

# Create a datetime object for December 25, 2021, 8:00:00 PM
my_datetime = datetime.datetime(2021, 12, 25, 20, 0, 0)

You can also create datetime objects for the current date and time using the now() method:

# Create a datetime object for the current date and time
current_datetime = datetime.datetime.now()

Datetime Formatting

You can format datetime objects into strings using the strftime() method, which allows you to specify a format string with various placeholders.

# Format a datetime object as a string
formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_datetime) # Output: 2023-06-10 15:30:00

Datetime Arithmetic

You can perform arithmetic operations on datetime objects, such as calculating time differences and adding or subtracting time intervals.

The result will be a timedelta object representing the difference or the modified datetime.

# Calculate the difference between two datetime objects
time_difference = current_datetime - my_datetime
print(time_difference) # Output: 167 days, 19:30:00

# Add a time interval to a datetime object
new_datetime = current_datetime + datetime.timedelta(days=7)