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.
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