Dates & Times
A date in Python is not a data type of its own, but we can import a module nameddatetime to work with dates as date objects.
1. Getting Current Time
import datetime
x = datetime.datetime.now()
print(x)
print(x.year)
print(x.strftime("%A")) # Full weekday name (e.g., Monday)
2. Creating Date Objects
To create a date, we can use the datetime() class of the datetime module.
d = datetime.datetime(2023, 5, 17)
print(d)
3. Formatting Dates (strftime)
The strftime() method takes one parameter, format, to specify the format of the returned string.
| Directive | Description | Example |
|---|
%Y | Year, full version | 2023 |
%m | Month as a number | 05 |
%d | Day of month | 17 |
%H | Hour (00-23) | 14 |
%M | Minute | 55 |
4. Date Arithmetic (timedelta)
from datetime import timedelta
tomorrow = x + timedelta(days=1)
last_week = x - timedelta(weeks=1)
print(tomorrow)
Tip: If you're working with complex timezones, the pytzlibrary is the professional standard for time-aware datetime objects in Python.