In this Tutorial -:

Python’s datetime module is a powerful tool that allows developers to work with dates and times effortlessly. Whether you need to display the current date, perform complex time-based calculations, or deal with timezones, the datetime module has got you covered. In this tutorial, we will explore the ins and outs of the datetime module, and by the end, you’ll be equipped with the knowledge to handle date and time operations effectively.
Introduction to the datetime Module
The datetime module is a built-in Python module that provides classes to represent dates, times, and durations. It is part of the standard library, so you don’t need to install any external packages to use it.
To begin, you must import the module at the beginning of your Python script or program:
import datetime
Understanding Date and Time Objects
Python’s datetime module includes several classes to represent date and time information:
-> datetime.date: Represents a date (year, month, day).
-> datetime.time: Represents a time of day (hour, minute, second, microsecond).
-> datetime.datetime: Represents both date and time.
-> datetime.timedelta: Represents the difference between two dates or times.
Obtaining the Current Date and Time
To get the current date and time, you can use the datetime.now() function from the datetime class:
import datetime
current_datetime = datetime.datetime.now()
print("Current Date and Time:", current_datetime)
O/P
Current Date and Time: 2023-07-23 16:33:46.415012
Fetching Day, Month, Year
import datetime
current_datetime = datetime.datetime.now()
print("Day", current_datetime.day)
print("Month", current_datetime.month)
print("Year", current_datetime.year)
O/P
Day 23
Month 7
Year 2023
Formatting Dates and Times with strftime()
You can format dates and times into strings using the strftime() method (string format time). It allows you to create custom date and time representations:
import datetime
current_datetime = datetime.datetime.now()
formatted_date = current_datetime.strftime("%Y-%m-%d")
formatted_time = current_datetime.strftime("%H:%M:%S")
print("Formatted Date:", formatted_date)
print("Formatted Time:", formatted_time)
O/P
Formatted Date: 2023-07-23
Formatted Time: 16:44:34
The %Y, %m, %d, %H, %M, and %S are format codes representing year, month, day, hour, minute, and second, respectively.
Parsing Dates and Times with strptime()
You can parse strings containing dates and times back into datetime objects using the strptime() method (string parse time):
import datetime
date_str = "2023-07-23"
parsed_date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
print("Parsed Date:", parsed_date)
O/P
Parsed Date: 2023-07-23 00:00:00
Date and Time Arithmetic
You can perform arithmetic operations with dates and times using the timedelta class. It represents a duration or difference between two points in time:
import datetime
current_datetime = datetime.datetime.now()
one_day = datetime.timedelta(days=1)
yesterday = current_datetime - one_day
tomorrow = current_datetime + one_day
print("Yesterday:", yesterday)
print("Tomorrow:", tomorrow)
O/P
Yesterday: 2023-07-22 16:49:19.576019
Tomorrow: 2023-07-24 16:49:19.576019
Working with Timezones
By default, Python’s datetime objects do not have time zone information. If you need to work with time zones, you can use the pytz library or the dateutil library, which provides an updated version of pytz.
To use dateutil, install it first:
pip install dateutil
Then, you can convert a naive datetime object (without timezone) to a timezone-aware datetime object:
import datetime
from dateutil import tz
# Create a naive datetime
naive_datetime = datetime.datetime(2023, 7, 23, 12, 0, 0)
# Define the target timezone
target_timezone = tz.gettz("America/New_York")
# Convert to timezone-aware datetime
aware_datetime = naive_datetime.astimezone(target_timezone)
print("Naive DateTime:", naive_datetime)
print("Timezone Aware DateTime:", aware_datetime)
O/P
Naive DateTime: 2023-07-23 12:00:00
Timezone Aware DateTime: 2023-07-23 12:00:00-04:00
Notice the appended -04:00 at the end. This indicates the time zone offset from UTC. The datetime object is now aware of the “America/New_York” time zone, and the offset -04:00 signifies that this time is four hours behind Coordinated Universal Time (UTC). This offset accounts for the Eastern Daylight Time (EDT) which is in effect during daylight saving time for the “America/New_York” time zone.
Handling Time Duration
The datetime module provides the timedelta class to represent a duration between two points in time. You can use this for various purposes, such as calculating differences between dates or adding/subtracting time intervals:
import datetime
# Create two datetime objects
start_datetime = datetime.datetime(2023, 7, 20, 10, 30, 0)
end_datetime = datetime.datetime(2023, 7, 23, 15, 45, 0)
# Calculate duration between them
duration = end_datetime - start_datetime
print("Duration:", duration)
O/P
Duration: 3 days, 5:15:00
The datetime module in Python is a powerful and versatile tool for working with dates and times. With its various classes and methods, you can easily manipulate dates, format and parse date strings, perform arithmetic with time intervals, and handle timezones.
