- Courses
- 💻Programming Languages
- 🐍Python
- Standard Library Deep Dive
- Datetime & Time
On this page
Datetime & Time
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Purpose of This Lesson
This lesson provides a complete, practical understanding of Python’s datetime and time modules.
You will learn how to:
- Represent dates, times, and combined datetimes
- Perform arithmetic with
timedelta - Parse and format timestamps
- Work with timezone‑aware datetimes
- Measure execution time
- Apply best practices for reliable, production‑grade time handling
Time manipulation is essential in automation, logging, scheduling, data engineering, and distributed systems.
Working with datetime
Creating Date, Time, and Datetime Objects
The datetime module provides three core classes:
date— calendar datestime— clock timesdatetime— full timestamps
Date
from datetime import date
d = date(2026, 4, 19)
Time
from datetime import time
t = time(22, 42, 0)
Datetime
from datetime import datetime
dt = datetime(2026, 4, 19, 22, 42, 0)
Getting the Current Date and Time
Local Time
from datetime import datetime
now = datetime.now()
UTC Time
from datetime import datetime, timezone
utc_now = datetime.now(timezone.utc)
Using UTC is a best practice for logging, distributed systems, and storage.
Datetime Arithmetic with timedelta
Use timedelta for date/time arithmetic.
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
one_hour_ago = now - timedelta(hours=1)
This is essential for scheduling, expiration logic, and time‑based calculations.
Parsing and Formatting Dates (strptime and strftime)
Parsing Strings → Datetime
from datetime import datetime
dt = datetime.strptime("2026-04-19 22:42", "%Y-%m-%d %H:%M")
Formatting Datetime → String
formatted = dt.strftime("%A, %d %B %Y")
Common format codes:
%Y— year%m— month%d— day%H— hour (24h)%M— minute%S— second
Parsing and formatting are essential for logs, APIs, and user interfaces.
Timezones and Aware Datetimes
Naive vs. Aware Datetimes
- Naive datetime: no timezone information
- Aware datetime: includes timezone offset
Always prefer aware datetimes for correctness.
Creating a Timezone‑Aware Datetime
from datetime import datetime, timezone
dt = datetime(2026, 4, 19, 22, 42, tzinfo=timezone.utc)
Converting Between Timezones
from datetime import timezone, timedelta
jst = timezone(timedelta(hours=9))
utc_dt = datetime.now(timezone.utc)
jst_dt = utc_dt.astimezone(jst)
Timezone conversion is critical for global applications.
Working with the time Module
Measuring Execution Time
Use time for precise timing.
time.time() — Wall Clock Time
import time
start = time.time()
# code block
end = time.time()
elapsed = end - start
time.perf_counter() — High‑Resolution Timer
Recommended for benchmarking.
import time
start = time.perf_counter()
# code block
elapsed = time.perf_counter() - start
Sleeping (Pausing Execution)
import time
time.sleep(2) # pause for 2 seconds
Useful for rate‑limiting, retries, and scheduling.
Best Practices for Datetime & Time
- Prefer
datetimeovertimefor most applications - Use UTC for storage, logs, and internal logic
- Convert to local time only for display
- Always use timezone‑aware datetimes in distributed systems
- Use
timedeltafor arithmetic, never manually add seconds - Use
perf_counter()for benchmarking - Avoid naive datetimes in production code
These practices ensure correctness, portability, and reliability.
Summary
This lesson provided a complete, practical foundation for working with dates, times, and timezones in Python.
You learned how to:
- Create and manipulate
date,time, anddatetimeobjects - Parse and format timestamps
- Perform arithmetic with
timedelta - Use timezone‑aware datetimes
- Measure execution time accurately
- Apply best practices for robust time handling
These skills are essential for any real‑world Python application that interacts with schedules, logs, automation, or distributed systems.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
OS & Filesystem
Next
Random & Secrets
-
Purpose of This Lesson
-
Working with
datetime- Creating Date, Time, and Datetime Objects
- Getting the Current Date and Time
-
Datetime Arithmetic with
timedelta -
Parsing and Formatting Dates (
strptimeandstrftime)- Parsing Strings → Datetime
- Formatting Datetime → String
-
Timezones and Aware Datetimes
- Naive vs. Aware Datetimes
- Creating a Timezone‑Aware Datetime
- Converting Between Timezones
-
Working with the
timeModule- Measuring Execution Time
- Sleeping (Pausing Execution)
-
Best Practices for Datetime & Time
-
Summary
