Next Topic ⮕
Python Built-in FunctionsPython datetime Module
Introduction to Python datetime
Time is a crucial element in programming — whether you're logging events, calculating durations, or scheduling tasks. Python makes handling dates and times easy and intuitive with its built-in datetime
module. This tutorial walks you through the foundational concepts of datetime
and shows you how to effectively use it in your code.
Importing the datetime Module
To begin working with dates and times, you first need to import the datetime
module:
import datetime
This gives you access to classes like datetime
, date
, time
, and timedelta
.
Creating a Date Object
The date
class lets you represent and manipulate dates (year, month, day).
from datetime import date
d = date(2025, 5, 16)
print(d)
2025-05-16
Explanation: This creates a date object for May 16, 2025. The output is in ISO format (YYYY-MM-DD).
Today's Date
Need to get today’s date? Use the today()
method.
from datetime import date
today = date.today()
print("Today is:", today)
Today is: 2025-05-16
Working with datetime Objects
The datetime
class combines both date and time into a single object.
from datetime import datetime
now = datetime.now()
print("Current date and time:", now)
Current date and time: 2025-05-16 08:23:45.123456
Notice that it includes the date, hour, minute, second, and microsecond. Perfect for timestamps.
Accessing Individual Components
You can extract parts of the datetime using its attributes.
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
Year: 2025
Month: 5
Day: 16
Hour: 8
Minute: 23
Second: 45
Formatting Dates and Times
Use the strftime()
method to convert a datetime object into a string with custom formatting.
formatted = now.strftime("%B %d, %Y %I:%M %p")
print("Formatted:", formatted)
Formatted: May 16, 2025 08:23 AM
Note: Use %B
for full month name, %d
for day, %Y
for 4-digit year, etc.
Parsing Strings into datetime Objects
Want to convert a date/time string into a datetime
object? Use strptime()
.
date_str = "2025-05-16 14:30"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt)
2025-05-16 14:30:00
Working with Timedelta
timedelta
is used to perform date/time arithmetic.
from datetime import timedelta
tomorrow = today + timedelta(days=1)
yesterday = today - timedelta(days=1)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)
Tomorrow: 2025-05-17
Yesterday: 2025-05-15
Measuring Time Durations
Let’s measure how long a piece of code takes to run:
start = datetime.now()
# Simulate processing
for _ in range(10**6):
pass
end = datetime.now()
duration = end - start
print("Processing time:", duration)
Processing time: 0:00:00.043200
Handling Time Zones
By default, datetime
objects are "naive" (no timezone). You can make them aware using pytz
or zoneinfo
(Python 3.9+).
from datetime import datetime
from zoneinfo import ZoneInfo
dt = datetime.now(ZoneInfo("Asia/Kolkata"))
print(dt)
2025-05-16 13:55:42.123456+05:30
Common Pitfalls & Tips
- Always verify input formats when using
strptime()
. A mismatch throwsValueError
. - Be mindful of time zones in global applications. Naive datetimes can lead to bugs.
- Use
timedelta
instead of manual calculations — it handles leap years, daylight saving, etc. strftime
does not validate format codes — use only valid directives.
Conclusion
The datetime
module is one of Python's most powerful and underused tools. From calculating date ranges to logging precise timestamps, it enables developers to write time-sensitive code that is both readable and reliable. By mastering its basics, you're unlocking a vital skill that’s essential for real-world programming.
Next Topic ⮕
Python Built-in Functions