The datetime
module in Python provides essential classes and functions for working with dates and times. It allows you to handle and manipulate date and time values, perform date arithmetic, and format dates to meet your needs. This tutorial covers all the basics and advanced usage of the datetime
module, complete with examples, explanations, and practical applications.
Python’s datetime
module provides classes and methods to work with dates, times, and time intervals. These classes make it easy to handle various operations, such as date manipulation, formatting, and parsing.
The datetime
module offers several advantages:
The datetime
module includes several classes, each serving a different purpose for managing dates and times.
datetime.date
ClassThe date
class represents a calendar date (year, month, day).
from datetime import date
# Create a date object
today = date.today()
print("Today's date:", today)
# Access year, month, and day
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
Today's date: YYYY-MM-DD
Year: YYYY
Month: MM
Day: DD
datetime.time
ClassThe time
class represents a time of day (hours, minutes, seconds, and microseconds).
from datetime import time
# Create a time object
t = time(14, 30, 45) # 2:30:45 PM
print("Time:", t)
# Access hour, minute, second
print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
Time: 14:30:45
Hour: 14
Minute: 30
Second: 45
datetime.datetime
ClassThe datetime
class combines both date and time into a single object.
from datetime import datetime
# Current date and time
now = datetime.now()
print("Now:", now)
# Specify date and time
specific_date_time = datetime(2023, 5, 17, 14, 30)
print("Specific date and time:", specific_date_time)
Now: YYYY-MM-DD HH:MM:SS
Specific date and time: 2023-05-17 14:30:00
The timedelta
class represents the difference between two dates or times. It’s useful for date arithmetic, such as adding or subtracting days.
from datetime import datetime, timedelta
# Current date and time
now = datetime.now()
# Add 5 days
future_date = now + timedelta(days=5)
print("Date 5 days from now:", future_date)
# Subtract 2 hours
past_time = now - timedelta(hours=2)
print("Time 2 hours ago:", past_time)
Date 5 days from now: YYYY-MM-DD HH:MM:SS
Time 2 hours ago: YYYY-MM-DD HH:MM:SS
The strftime
method allows you to format dates and times into readable strings.
%Y
: Year with century (e.g., 2023)%m
: Month as a zero-padded decimal number (e.g., 01, 12)%d
: Day of the month as a zero-padded decimal number (e.g., 01, 31)%H
: Hour (24-hour clock)%M
: Minute%S
: Secondfrom datetime import datetime
now = datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
Formatted date: YYYY-MM-DD HH:MM:SS
The strptime
method allows you to parse strings into datetime objects, making it easy to convert formatted strings back to dates and times.
from datetime import datetime
date_str = "2023-05-17 14:30:00"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print("Parsed date:", parsed_date)
Parsed date: 2023-05-17 14:30:00
The datetime
module supports time zones through the timezone class, allowing you to handle dates and times across different regions.
from datetime import datetime, timezone, timedelta
# Define a UTC offset
utc_offset = timezone(timedelta(hours=-5))
# Create a timezone-aware datetime
now = datetime.now(utc_offset)
print("Time with UTC offset:", now)
Time with UTC offset: YYYY-MM-DD HH:MM:SS-05:00
from datetime import datetime
def calculate_age(birthdate):
today = datetime.today()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
return age
# Test the function
birthdate = datetime(1990, 5, 17)
print("Age:", calculate_age(birthdate))
from datetime import datetime, timedelta
def schedule_event(days_from_now):
now = datetime.now()
event_date = now + timedelta(days=days_from_now)
return event_date
# Schedule an event for 10 days from now
print("Event date:", schedule_event(10))
When working with time zones, ensure that both datetime
objects are either timezone-aware or naive (without timezone info) to avoid errors.
from datetime import datetime, timezone
# Define timezone-aware datetime
dt1 = datetime.now(timezone.utc)
dt2 = datetime(2023, 5, 17) # naive datetime
# Uncommenting the line below will raise an error
# print(dt1 - dt2)
strptime
for ParsingParsing a date string without using strptime
can lead to errors. Always use the correct format code when parsing.
date_str = "2023-05-17"
# Use strptime for parsing
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
timedelta
IncorrectlyBe mindful of the units in timedelta
. For instance, adding 1 month requires a more complex calculation as timedelta
doesn’t have months.
datetime
Module: Essential for handling dates, times, and time intervals.date
, time
, datetime
, and timedelta
provide all the functionality needed for date and time operations.strftime
to format dates and strptime
to parse strings into dates.timedelta
for adding or subtracting days, hours, or minutes.The datetime
module in Python is a powerful tool for managing dates and times, providing classes for handling individual dates
, times
, combined datetime
objects, and timedeltas
. By understanding how to format, parse, and manipulate dates, you can handle tasks such as scheduling, age calculation, time zone adjustments, and more. With datetime, your Python programs can effectively manage date and time data in various real-world scenarios.
With Python’s datetime module, you can:
timedelta
for adding or subtracting time.strftime
and strptime
to convert dates to strings and vice versa.Ready to implement date and time operations in your projects? Try using the datetime
module to add timestamps, handle time zones, and perform date calculations. Happy coding!