Working with Dates and Time
Learn how to handle dates, times, and timestamps using Python's datetime module.
Learning Objectives
- Import and use the datetime module
- Create and format dates and times
- Calculate time differences (durations)
- Understand UTC vs. local time basics
Timing is Everything
Many applications need to keep track of time: when a user registered, when a task is due, or how much time has passed since an event. Python’s built-in datetime module is the standard tool for this.
Importing Datetime
To use it, you first need to import it.
|
|
Creating Specific Dates
|
|
Formatting Dates (strftime)
Computers like timestamps, but humans like formatted strings. We use strftime (string format time) to turn dates into readable text.
|
|
Calculating Durations (timedelta)
You can subtract dates to see how much time is between them.
|
|
Interactive Practice
Try calculating how many days old you are by subtracting your birth date from today’s date!
| Code | Output | Description |
|---|---|---|
%Y |
2026 | 4-digit year |
%B |
January | Full month name |
%A |
Thursday | Full weekday name |
%H |
14 | 24-hour clock |
Quiz
Complete this quiz with a minimum score of 80% to mark Day 20 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!