Skip to Content
Course content

219: Parsing and Formatting Dates

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Dates are notoriously annoying in software engineering. One API gives you a Unix timestamp, another gives you an ISO string, and some legacy system might give you something like "15-Oct-2023". The trick is knowing how to move between these strings and actual Python datetime objects.

How do I actually turn a date string into a Python object?

You'll want to use strptime, which stands for "string parse time." Think of it as telling Python: "Here is a string, and here is the map of how to read it." If the map doesn't match the string exactly, Python will throw a fit.

from datetime import datetime

# Let's say we're parsing a log entry from a server
log_timestamp = "2023-11-15 08:45:12"
format_map = "%Y-%m-%d %H:%M:%S"

# We pass the string first, then the map
date_obj = datetime.strptime(log_timestamp, format_map)

print(f"Successfully parsed: {date_obj}")
print(f"The year is {date_obj.year}")

Wait, what do all those % symbols actually mean?

I'll be honest: nobody memorizes all of these. I still keep a cheat sheet open in my browser. The % codes are placeholders for specific parts of the date. The most common ones you'll use are %Y for a four-digit year, %m for month (01-12), and %d for the day of the month.

  • %Y: 2023 (4-digit year)
  • %y: 23 (2-digit year)
  • %B: November (Full month name)
  • %b: Nov (Abbreviated month name)
  • %H: 24-hour clock
  • %M: Minutes
  • %S: Seconds

Just remember that %m is for month and %M is for minute. It's a common slip-up that leads to some very weird bugs in production.

Now that I have a date object, how do I make it look pretty?

Once you have a datetime object, you use strftime ("string format time"). This is the inverse of parsing. Instead of reading a string, you're telling Python how to build one. This is where you make the date human-readable for your UI or a report.

from datetime import datetime

now = datetime.now()

# Let's create a friendly, readable timestamp for a user
# "Wednesday, Nov 15, 2023 - 08:45 AM"
pretty_date = now.strftime("%A, %b %d, %Y - %I:%M %p")

print(pretty_date)

What happens if the input date format is inconsistent?

In the real world, data is messy. If you tell strptime to expect %Y-%m-%d but it receives 11/15/2023, it will raise a ValueError. If you're parsing a file with thousands of lines, one bad date can crash your entire script. I always wrap my parsing logic in a try-except block.

from datetime import datetime

dates_to_parse = ["2023-11-15", "invalid-date", "2023-11-16"]

for date_str in dates_to_parse:
    try:
        parsed = datetime.strptime(date_str, "%Y-%m-%d")
        print(f"Parsed {date_str} successfully.")
    except ValueError:
        print(f"Skipping malformed date: {date_str}")



📋 Practical Task

Exercise: The Legacy Log Standardizer

You've been handed a legacy log file where the dates are formatted in a non-standard way: "Day/Month/Year Hour:Minute" (e.g., "25/12/2022 14:30"). Your boss wants these converted into the ISO 8601 standard format ("YYYY-MM-DD HH:MM:SS") so they can be imported into a modern database.

Write a function called standardize_log_date that takes a string in the legacy format and returns a string in the ISO format. If the input string is invalid, the function should return the string "INVALID DATE".

# Test your function with these cases:
# "25/12/2022 14:30" -> "2022-12-25 14:30:00"
# "01/01/2023 00:00" -> "2023-01-01 00:00:00"
# "bad-date"         -> "INVALID DATE"
Rating
0 0

There are no comments for now.

to be the first to leave a comment.