Python Datetime Module
The datetime module supplies classes for manipulating dates and times. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.
Importing the Module
import datetime
Common Classes
datetime.date: An idealized naive date, assuming the current Gregorian calendar extended in both directions. Attributes: year, month, and day.datetime.time: An idealized time, independent of any particular day, assuming that every day has exactly 246060 seconds. Attributes: hour, minute, second, microsecond, and tzinfo.datetime.datetime: A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.datetime.timedelta: A duration expressing the difference between two date, time, or datetime instances.
Working with Dates
Getting Today's Date
from datetime import date
today = date.today()
print("Today's date:", today)
Creating Date Objects
d = date(2023, 4, 13)
print(d)
Working with Datetime
Getting Current Date and Time
from datetime import datetime
now = datetime.now()
print("now =", now)
Creating Datetime Objects
dt = datetime(2023, 11, 28, 23, 55, 59, 342380)
print("dt =", dt)
Date Arithmetic (timedelta)
timedelta objects represent a duration, the difference between two dates or times.
from datetime import date, timedelta
today = date.today()
print("Today:", today)
# Add 7 days
next_week = today + timedelta(days=7)
print("Next week:", next_week)
# Subtract 1 day
yesterday = today - timedelta(days=1)
print("Yesterday:", yesterday)
Formatting and Parsing
strftime() - Date to String
The strftime() method creates a string representing the date under the control of an explicit format string.
from datetime import datetime
now = datetime.now()
# Format: DD/MM/YYYY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
strptime() - String to Date
The strptime() method creates a datetime object from a given string (representing date and time).
from datetime import datetime
date_string = "21 June, 2023"
dt_object = datetime.strptime(date_string, "%d %B, %Y")
print("dt_object =", dt_object)
Common Format Codes
%Y: Year with century as a decimal number.%m: Month as a decimal number [01,12].%d: Day of the month as a decimal number [01,31].%H: Hour (24-hour clock) as a decimal number [00,23].%M: Minute as a decimal number [00,59].%S: Second as a decimal number [00,61].