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.

DirectiveDescriptionExample
%YYear, full version2023
%mMonth as a number05
%dDay of month17
%HHour (00-23)14
%MMinute55

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.