Date helpers
- Python course
- Intermediate
- Lesson 16/116
- 6 min
Add datetime processing methods.
The format_date method
We'll write a format_date method to show dates in one form. format_date(year, month, day) returns a string in YYYY-MM-DD form; single digit months and days are zero padded.
Example: format_date(2024, 5, 1) → "2024-05-01". We use an f-string with the :02d format: f"{year:04d}-{month:02d}-{day:02d}". :04d pads the year to four digits, :02d pads month/day to two.
f-string formatting
Inside an f-string, {value:format} turns the value into the given format. :02d writes an integer with at least two digits, padded with zeros; :04d pads to four digits.
Example: f"{5:02d}" → "05", f"{2024:04d}" → "2024". Literal characters like - are written as is. This lets us format dates in one line.
Practice Add format_date to Utility
Add a def format_date(self, year, month, day): method to the Utility class. In the body write return f"{year:04d}-{month:02d}-{day:02d}". Then create an instance with u = Utility() and call print(u.format_date(2024, 5, 1)).
Starter code
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
u = Utility()
print(u.clamp(15, 0, 10))
# Add the format_date method and call it on an instanceSample solution
class Utility:
version = "1.0"
def slugify(self, text):
return text.lower().replace(" ", "-")
def clamp(self, n, lo, hi):
return max(lo, min(hi, n))
def format_date(self, year, month, day):
return f"{year:04d}-{month:02d}-{day:02d}"
u = Utility()
print(u.format_date(2024, 5, 1))Expected output
2024-05-01
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the format_date signature
class Utility:
def format_date(self, year, month, ____):
return f"{year:04d}-{month:02d}-{day:02d}"
class Utility:
def format_date(self, year, month, day):
return f"{year:04d}-{month:02d}-{day:02d}"
Explanation: The day parameter takes the day value; it is formatted with :02d in the f-string.
2 Match the format_date parts
| Term | Meaning |
|---|---|
format_date |
Method name |
:02d |
Zero padding |
2024-05-01 |
Output |
3 What does format_date(2024, 5, 1) return?
- 2024-5-1
- 2024/05/01
- 05-01-2024
- 2024-05-01 Correct answer
Explanation: :02d pads month and day with zeros; the separator is a hyphen.