Python Dates
Python does not have a built-in date data type of its own, so you import the datetime module to work with dates, times, and time intervals. A datetime object contains information such as year, month, day, hour, minute, second, and microsecond.
1. Current Date & Time
Use datetime.datetime.now() to get the current date and time, or access individual attributes like year, month, and day:
import datetime
now = datetime.datetime.now()
print("Current Date & Time:", now)
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
2. Creating a Specific Date Object
To create a specific date, pass year, month, and day (in that order) to the datetime() class constructor:
import datetime
launch_date = datetime.datetime(2026, 8, 15)
print("Launch Date:", launch_date)
3. Formatting Dates with strftime()
The strftime() method formats a datetime object into a readable string using format codes like %Y (4-digit year), %B (full month name), %d (day of month), and %A (weekday name):
import datetime
today = datetime.datetime.now()
print("Formatted (DD-MM-YYYY):", today.strftime("%d-%m-%Y"))
print("Full Readable Date:", today.strftime("%A, %d %B %Y"))
4. Date Arithmetic with timedelta
Use datetime.timedelta to add or subtract days, weeks, or hours from a date:
import datetime
current = datetime.datetime.now()
next_week = current + datetime.timedelta(days=7)
yesterday = current - datetime.timedelta(days=1)
print("Yesterday:", yesterday.strftime("%Y-%m-%d"))
print("Next Week:", next_week.strftime("%Y-%m-%d"))
strftime() to convert a datetime object into a formatted string, and strptime() when you need to parse a date string back into a datetime object.