Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
219: Parsing and Formatting Dates
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"
There are no comments for now.