Module: M3-R5: Python Programming
Chapter: Functions
Python provides the datetime module to work with dates and times, including formatting, arithmetic, and conversions.
Returns current local date and time.
from datetime import datetime
now = datetime.now()
print(now)Output:
2025-10-19 20:45:30.123456 (varies)Returns current local date without time info.
from datetime import datetime
today = datetime.today()
print(today)Output:
2025-10-19 20:45:30.123456 (varies)Creates a date object (year, month, day).
from datetime import date
my_date = date(2025, 10, 19)
print(my_date)Output:
2025-10-19Creates a time object (hour, minute, second).
from datetime import time
my_time = time(14, 30, 45)
print(my_time)Output:
14:30:45Represents a duration, used for date arithmetic.
from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=5)
print(future)Output:
2025-10-24 20:45:30.123456 (varies)
Formats date as YYYY-MM-DD.
from datetime import datetime
now = datetime.now()
print(now.strftime('%Y-%m-%d'))Output:
2025-10-19Formats date as DD/MM/YYYY.
from datetime import datetime
now = datetime.now()
print(now.strftime('%d/%m/%Y'))Output:
19/10/2025Formats date with full weekday and month names.
from datetime import datetime
now = datetime.now()
print(now.strftime('%A, %B %d, %Y'))Output:
Sunday, October 19, 2025Formats time in 12-hour format with AM/PM.
from datetime import datetime
now = datetime.now()
print(now.strftime('%I:%M %p'))Output:
08:45 PMFormats time in 24-hour format.
from datetime import datetime
now = datetime.now()
print(now.strftime('%H:%M:%S'))Output:
20:45:30
Short weekday, day, short month, year.
from datetime import datetime
now = datetime.now()
print(now.strftime('%a, %d %b %Y'))Output:
Sun, 19 Oct 2025Day of the year (001-366).
from datetime import datetime
now = datetime.now()
print(now.strftime('%j'))Output:
292Week number of the year (Sunday as first day).
from datetime import datetime
now = datetime.now()
print(now.strftime('%U'))Output:
42