Date/Time Formatting and Manipulation
You've built datetime objects from user input and understand the basics of timezone awareness. Now you'll learn how to format those objects for display and manipulate them to solve real-world scheduling problems. By the end of this lesson, you'll format dates for different audiences, calculate durations, and convert times across timezones—the exact skills you need for building global applications.
Why Formatting Matters
Think about your favorite app. When it shows you an event time, it doesn't say "2025-11-09T14:30:00+00:00" (that's for computers). It says something like "Sunday, November 9 at 2:30 PM" or "2025-11-09" depending on context. The raw datetime object is useless to humans without formatting.
Similarly, when you're building a scheduling feature or calculating project deadlines, you need to manipulate dates—add days, subtract hours, find the difference between two moments. That's where timedelta comes in.
And when your app serves users around the world, you need to convert between timezones correctly. A meeting at 9 AM UTC is 4 AM EST—not handling that properly creates chaos.
This lesson teaches you all three skills, emphasizing that you don't memorize all 30+ format codes. You understand the pattern and ask AI when needed.
Formatting Dates and Times with strftime()
Strings. That's how humans read dates. The strftime() method converts datetime objects into human-readable text using format codes.
Understanding Format Codes
Each format code starts with % and represents a specific part of the date:
Loading Python environment...
The key insight: You don't memorize all 30+ codes. You learn the common ones (%Y, %m, %d, %H, %M, %S, %A, %B) and ask AI when you need something specific.
💬 AI Colearning Prompt
"Explain the difference between
%Yand%y, and between%Hand%I. When would you use each?"
Common Format Patterns
Here are the patterns you'll use most often:
Loading Python environment...
Notice how the same moment looks different depending on the format. Your job isn't to remember these strings—it's to choose the right format for your audience.
🎓 Expert Insight
In AI-native development, you don't memorize all 30+ format codes. You understand the pattern (
%Y= year,%m= month,%d= day) and ask AI when you need a specific format. Syntax is cheap; knowing WHEN to use ISO 8601 vs localized format is gold. ISO for data storage and APIs. Friendly format for user interfaces.
Practical Formatting Exercise
Let's build a function that formats a datetime in multiple ways:
Loading Python environment...
This function shows the real-world pattern: capture different formats once, use them throughout your application.
🚀 CoLearning Challenge
Ask your AI Co-Teacher:
"Generate code that formats a datetime in both ISO 8601 and 'Meeting on Saturday, 2:30 PM' format. Then explain what each format code does."
Expected Outcome: You'll understand how to combine format codes to create human-friendly output.
Working with Time Differences: Timedelta
A timedelta represents a duration—the difference between two points in time. Unlike datetime (which represents a specific moment), timedelta represents "how much time."
Creating Timedelta Objects
Loading Python environment...
Timedelta objects know how to convert between units automatically.
Date Arithmetic: Adding and Subtracting
Now here's where timedelta shines. Add it to a datetime to get a future date:
Loading Python environment...
Timedelta handles all the complexity for you—leap years, different month lengths, everything.
✨ Teaching Tip
Use Claude Code to explore edge cases: "Add 30 days to January 15. Then check: does it land on Feb 14? Why not 45 days?" This teaches you timedelta respects calendar reality.
Calculating Duration Between Two Moments
One of the most practical uses: find how much time has passed or remains:
Loading Python environment...
Notice we calculate remaining and check if it's positive. This is the pattern for deadlines, event scheduling, and countdowns.
🎓 Expert Insight
You're not calculating duration by hand (that's error-prone and wasteful). You subtract two datetime objects and timedelta does the work. Syntax is cheap; knowing to subtract datetime objects and handle the result is gold. This is why we use timedelta.
Code Example: Duration Calculation with Validation
Loading Python environment...
This function shows a real pattern: calculate timedelta, extract components, format for humans.
Converting Between Timezones
Timezones are your biggest challenge in datetime work. A time can't be "correct" or "incorrect" without a timezone—you need to know: "4 PM what? UTC? EST? JST?"
The Timezone Object
Python represents timezone offsets with the timezone class:
Loading Python environment...
The :−5 (negative 5) means "5 hours behind UTC." When it's noon UTC, it's 7 AM Eastern.
💬 AI Colearning Prompt
"Explain why timezone offsets are negative for Western Hemisphere and positive for Eastern Hemisphere."
Converting UTC to Local Time
Here's the practical scenario: you have a UTC timestamp (from a database), and you need to show the user their local time.
Loading Python environment...
The magic: astimezone() adjusts both the time AND the offset automatically.
🚀 CoLearning Challenge
Ask your AI Co-Teacher:
"Generate a function that takes a UTC timestamp and returns a dictionary with the time in NYC, London, and Tokyo timezones. Then explain what astimezone() does under the hood."
Expected Outcome: You'll understand how to display times for a global audience.
Real-World Timezone Conversion: Meeting Scheduler
Loading Python environment...
Output:
MEETING AGENDA
NYC: Sunday 09:30 AM
London: Sunday 02:30 PM
Tokyo: Monday 11:30 PM
This is real production code. You're solving an actual problem: helping people understand when a meeting happens in their timezone.
🎓 Expert Insight
You don't calculate timezone offsets in your head (that's why timezones exist as objects). You understand: "UTC is the reference, offsets are +/- hours, astimezone() does the conversion." Syntax is cheap; knowing to keep everything in UTC internally and convert on display is gold. This pattern prevents bugs.
Handling Timezone Edge Cases
Timezones aren't simple. During daylight saving time transitions, an hour doesn't exist (spring forward) or exists twice (fall back). For now, know this happens and use AI when you encounter it.
✨ Teaching Tip
When building a production scheduling system, ask your AI: "How do I handle times during DST transitions? When a time is ambiguous, which version should I pick?" This is where you lean on AI expertise—it's complex enough that asking beats guessing.
Summary of Formatting and Manipulation
Formatting with strftime(): Convert datetime objects to human-readable strings using format codes. You know the common ones (%Y, %m, %d, %H, %M, %S, %A, %B) and ask AI for others.
Manipulation with timedelta: Represent durations, add/subtract from datetimes, calculate differences. Always subtract datetime objects rather than calculating durations manually.
Conversion with timezone and astimezone(): Keep your system in UTC internally, convert to local timezones for display. Never hardcode timezone offsets—use timezone objects.
Try With AI
Apply datetime formatting and timezone conversion through AI collaboration that builds production skills.
🔍 Explore Format Codes:
"Format datetime(2025, 11, 9, 14, 30, 0, tzinfo=timezone.utc) in ISO 8601, US friendly ('Saturday, November 9 at 2:30 PM'), and log format. Explain when to use each in applications."
🎯 Practice Timedelta Operations:
"Add timedelta(days=5, hours=3, minutes=30) to current datetime. Subtract two datetimes to get duration. Extract and display components as 'X days, Y hours, Z minutes'."
🧪 Test Timezone Conversion:
"Create UTC datetime, convert to US/Eastern (UTC-5), Europe/London (UTC+0), and Asia/Tokyo (UTC+9) using astimezone(). Show how the same moment appears in each timezone."
🚀 Apply Multi-Format Display:
"Build a meeting scheduler that takes UTC time, converts to 3 timezones, formats each as 'City: Day HH:MM AM/PM', and explains why storing in UTC matters."