The datetime module is essential when handling dates and times in Python. By using this module, you can retrieve the current time, convert date‑time formats, perform time calculations, and many other operations. However, for Python beginners, dealing with datetime can feel a bit challenging. For example:
“I want to get the current date and time, but which function should I use?”
“I don’t know how to handle time zones!”
“How do I perform date calculations?”
This article clearly explains the basics to advanced usage of Python’s datetime module. Even beginners will be able to understand smoothly, as we include code examples, so please use it as a reference.
2. datetime Module? Understand the Basic Concepts
2.1 Overview of the datetime module
Python includes the datetime module as part of its standard library, allowing easy manipulation of dates and times. The datetime module contains the following major classes.
Class Name
Description
datetime
Class for handling dates and times
date
Class for handling dates only
time
Class for handling times only
timedelta
Class representing a duration
tzinfo
Class for handling time zone information
Among these, the datetime class is the most commonly used.
2.2 How to import the datetime module
To use Python’s datetime module, you first need to import it. Using import datetime as shown below imports the entire module.
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(now)
You can also import only specific classes.
from datetime import datetime
# Get the current date and time
now = datetime.now()
print(now)
Importing in the form from datetime import datetime allows you to avoid writing datetime twice in code, such as datetime.datetime.now(), making it simpler.
3. How to get the current time and today’s date in Python (difference between now and today)
3.1 How to get the current date and time
In Python, to obtain the current date and time, use datetime.now().
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
When you run this code, you get output like the following.
Current date and time: 2025-02-01 12:34:56.789012
This format is YYYY-MM-DD HH:MM:SS.ssssss, which includes the date, time, and microseconds.
3.2 How to get today’s date
If you only want today’s date, use date.today().
from datetime import date
today = date.today()
print("Today's date:", today)
Example output:
Today's date: 2025-02-01
3.3 Difference between now() and today()
Method
Function
datetime.now()
Gets the current date and time
date.today()
Gets the current date only
Choose the appropriate one based on your use case.
4. Date and Time Format Conversion (String ⇔ datetime)
When working with dates and times, format conversion is extremely important. In Python, you can use strftime() and strptime() to convert between datetime objects and strings.
4.1 Converting a datetime object to a string (strftime)
If you want to convert a datetime to a string in a specific format, use strftime().
from datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
Output:
Formatted date: 2025-02-01 12:34:56
4.2 Converting a string to a datetime object (strptime)
To convert a string to a datetime, use strptime().
5. How to add and subtract dates in Python (using timedelta)
In Python, you can easily perform addition and subtraction of dates and times by using the timedelta class.
5.1 Basics of the timedelta class
from datetime import datetime, timedelta
# Get the current date and time
now = datetime.now()
# Get the date 7 days from now
future_date = now + timedelta(days=7)
print("Date 7 days from now:", future_date)
# Get the date 3 days ago
past_date = now - timedelta(days=3)
print("Date 3 days ago:", past_date)
5.2 Adding and subtracting in time units
from datetime import datetime, timedelta
now = datetime.now()
# Time one hour later
one_hour_later = now + timedelta(hours=1)
print("Time one hour later:", one_hour_later)
# Time 30 minutes ago
thirty_minutes_ago = now - timedelta(minutes=30)
print("Time 30 minutes ago:", thirty_minutes_ago)
6. Handling Dates and Times with Time Zone Awareness (Differences between pytz and zoneinfo)
When handling dates and times in Python, taking time zones into account is extremely important.
6.1 pytz Setting Time Zones
from datetime import datetime
import pytz
# Specify the time zone
japan_tz = pytz.timezone('Asia/Tokyo')
# Get the current UTC time
utc_now = datetime.utcnow()
# Convert to JST (Japan Standard Time)
jst_now = utc_now.replace(tzinfo=pytz.utc).astimezone(japan_tz)
print("Japan Time (JST):", jst_now)
6.2 zoneinfo (Python 3.9 and later) Setting Time Zones
from datetime import datetime
from zoneinfo import ZoneInfo
# Get the current time in JST (Japan Standard Time)
jst_now = datetime.now(ZoneInfo("Asia/Tokyo"))
print("Current JST time:", jst_now)
If you are using Python 3.9 or later, it is recommended to use zoneinfo.
7. Errors and Their Solutions
When using Python’s datetime module, there are several errors that beginners often encounter.
7.1 AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
from datetime import datetime
# Trying to use timedelta but error
now = datetime.now()
new_date = now + datetime.timedelta(days=7)
Solution:
from datetime import datetime, timedelta
now = datetime.now()
new_date = now + timedelta(days=7)
print(new_date)
7.2 TypeError: can't subtract offset-naive and offset-aware datetimes
from datetime import datetime, timedelta
start_date = datetime(2025, 2, 1)
end_date = datetime(2025, 2, 7)
date_list = [start_date + timedelta(days=i) for i in range((end_date - start_date).days + 1)]
for date in date_list:
print(date.strftime("%Y-%m-%d"))
8.2 Date Calculations Considering Business Days (Weekdays)
import pandas as pd
business_days = pd.bdate_range(start="2025-02-01", end="2025-02-10")
for day in business_days:
print(day.date())
✅ Develop a schedule management app ✅ Analyze log data ✅ Perform time calculations across different time zones ✅ Implement an automatic reminder feature Thank you for reading to the end!