Python provides powerful tools for working with dates and times through the built-in datetime module. This module allows you to:
Learn Python Programming and become a certified software developer
Let’s break it down.
import datetime You can also import specific classes:
Learn Python Programming Online
from datetime import date, time, datetime, timedelta The date class represents a calendar date (year, month, day).
from datetime import date
d = date(2025, 12, 1)
print(d) # 2025-12-01 today = date.today()
print(today) # Example: 2025-12-01 print(today.year)
print(today.month)
print(today.day) The time class represents a time of day (without date).
from datetime import time
t = time(14, 30, 45)
print(t) # 14:30:45 print(t.hour)
print(t.minute)
print(t.second)
print(t.microsecond) The datetime class combines both date + time.
from datetime import datetime
dt = datetime(2025, 12, 1, 14, 30, 45)
print(dt) now = datetime.now()
print(now) utc_now = datetime.utcnow()
print(utc_now) Use .strftime() to convert a date/time object into a formatted string.
%Y → Year%m → Month%d → Day%H → Hour%M → Minute%S → Second%A → Day namenow = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted) Use .strptime() to convert a string into a datetime object.
from datetime import datetime
date_string = "2025-12-01 14:30:45"
parsed = datetime.strptime(date_string, "%Y-%m-%d %H:%M:%S")
print(parsed) Python uses timedelta for arithmetic.
from datetime import timedelta
future = today + timedelta(days=10)
print(future) past = today - timedelta(days=7)
print(past) d1 = date(2025, 1, 1)
d2 = date(2025, 12, 1)
diff = d2 - d1
print(diff.days) # number of days Python 3.9+ uses zoneinfo for timezone support.
from datetime import datetime
from zoneinfo import ZoneInfo
lagos_time = datetime.now(ZoneInfo("Africa/Lagos"))
print(lagos_time)
new_york_time = datetime.now(ZoneInfo("America/New_York"))
print(new_york_time)
dt = datetime(2025, 12, 1, 14, 0, tzinfo=ZoneInfo("Africa/Lagos"))
converted = dt.astimezone(ZoneInfo("America/New_York"))
print(converted) Sometimes you need delays (not part of datetime).
import time
time.sleep(2) # pause for 2 seconds datetime for timestampszoneinfo instead of old pytz.strftime() and .strptime() for formatting/parsingtimedelta for safe arithmeticLatest tech news and coding tips.
A SOC Analyst (Security Operations Center Analyst) is one of the frontline defenders of an organization’s cybersecurity…
Most image upload systems assume one thing: the user has a stable internet connection. That assumption…
Imagine a user submits a form while their internet connection suddenly disappears. Normally, the request…
Cybercriminals don't always announce their presence. Many compromises are designed to remain unnoticed for weeks…
For years, jQuery was everywhere. If you were building websites in the 2010s, there was a…
Few things halt a developer’s flow faster than seeing the dreaded word: CONFLICT. A Git merge…