Python Date, Time & DateTimeImmutable Objects
Handling dates and timezones reliably is vital for web backends. Learn legacy timestamp formatting via date() and time(), and transition to modern object-oriented DateTimeImmutable, DateInterval, and timezone conversions.
"A raw UNIX timestamp is just a ticking counter of seconds since 1970. A DateTimeImmutable object is a precision atomic clock that knows the exact local daylight savings time in Tokyo, London, or New York."
Deep Dive: How It Works
Legacy date(): date("Y-m-d H:i:s") formats the current server timestamp.
DateTimeImmutable: Modern immutable object that returns a fresh instance on modification, preventing mutation bugs.
Timezones: Set default with date_default_timezone_set("UTC") or pass new DateTimeZone("America/New_York").
Date Intervals: $date->add(new DateInterval("P7D")) adds 7 days cleanly.
Syntax Blueprint
<?php
$now = new DateTimeImmutable("now", new DateTimeZone("UTC"));
$nextWeek = $now->modify("+7 days");
echo $nextWeek->format("Y-m-d");Create DateTimeImmutable instances, modify with human intervals (+7 days), and format with format().
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Using mutable DateTime and modifying it inside a helper function, inadvertently mutating the original caller date.Why it happens: DateTime methods mutate the object in place.
How to fix: Switch to DateTimeImmutable.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Calculate Event Expiration Date
Create a DateTimeImmutable from "2026-01-01".
Add 30 days using modify("+30 days").
Print "Trial Ends: [Y-m-d]".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.