The datetime module in Python provides classes for manipulating dates and times. It supports operations like formatting, parsing, arithmetic, and comparisons. Below are key features of the datetime module along with example code snippets.
1. Getting the Current Date and Time
The datetime module allows you to get the current date and time using the datetime.now() function.
You can create specific date, time, or datetime objects by passing arguments to their constructors.
from datetime import date, time, datetime# Create a specific datespecific_date =date(2022,5,17)print(specific_date)# Output: 2022-05-17# Create a specific timespecific_time =time(14,30,0)print(specific_time)# Output: 14:30:00# Create a specific datetimespecific_datetime =datetime(2022,5,17,14,30,0)print(specific_datetime)# Output: 2022-05-17 14:30:00
3. Formatting Dates and Times
You can format datetime objects into readable strings using the strftime() method. The method takes a format string with placeholders.
Some commonly used format codes:
%Y: Year with century (e.g., 2025)
%m: Month as a zero-padded decimal number (e.g., 01)
%d: Day of the month (e.g., 22)
%H: Hour (24-hour clock) (e.g., 12)
%M: Minute (e.g., 00)
%S: Second (e.g., 59)
4. Parsing Dates and Times
You can parse a string representation of a date or time into a datetime object using strptime().
5. Date Arithmetic (Adding and Subtracting Dates)
You can perform arithmetic on datetime objects using timedelta objects, which represent a difference between two dates or times.
6. Comparing Dates and Times
You can compare datetime objects using comparison operators (>, <, ==, etc.).
You can also compare time and datetime objects similarly.
7. Working with Time Zones (Using pytz)
The datetime module works with time zones through timezone objects. However, to manage time zones more effectively, you can use the pytz library.
8. Getting the Day of the Week
You can get the day of the week as an integer (0 for Monday, 6 for Sunday) using the .weekday() method, or as a string using .strftime("%A").
9. Working with Time Delays
You can pause the execution of your program for a certain period using time.sleep(), which can be useful for tasks like rate-limiting or scheduling.
10. Handling Time Zones with datetime Module
You can work with fixed offset time zones using the timezone class within the datetime module.
Summary of Common datetime Module Features:
datetime.now(): Get the current date and time.
strftime(): Format a datetime object as a string.
strptime(): Parse a string into a datetime object.
from datetime import timedelta
# Add 10 days to the current date
current_date = datetime.date.today()
new_date = current_date + timedelta(days=10)
print(new_date) # Output: 2025-02-01 (example)
# Subtract 3 hours from the current time
current_time = datetime.datetime.now().time()
new_time = (datetime.datetime.combine(datetime.date.today(), current_time) - timedelta(hours=3)).time()
print(new_time) # Output: 09:00:00 (example)
import pytz
from datetime import datetime
# Get the current time in UTC
utc_time = datetime.now(pytz.utc)
print("UTC Time:", utc_time)
# Convert UTC time to a specific time zone (e.g., US/Eastern)
eastern_time = utc_time.astimezone(pytz.timezone('US/Eastern'))
print("Eastern Time:", eastern_time)
current_date = datetime.date.today()
# Get the day of the week as an integer (0=Monday, 6=Sunday)
day_of_week = current_date.weekday()
print(day_of_week) # Output: 1 (for Tuesday)
# Get the day of the week as a string
day_name = current_date.strftime("%A")
print(day_name) # Output: "Tuesday"
import time
print("Starting countdown...")
time.sleep(5) # Delay for 5 seconds
print("5 seconds have passed.")
from datetime import datetime, timezone, timedelta
# Define a timezone with a 5-hour offset
tz = timezone(timedelta(hours=5))
# Get current datetime in this timezone
current_time = datetime.now(tz)
print(current_time) # Output: 2025-01-22 17:00:00+05:00