๐ Python datetime Module โ Working with Dates and Times
Python's datetime module handles dates, times, timezones, and arithmetic. Essential for logs, scheduling, and data pipelines.
Always store dates in UTC in your database. Convert to local timezone only when displaying to users.
๐ป Code Example:
from datetime import datetime, timedelta, date, timezone # 1. Current date and time now = datetime.now() print(now) # 2026-04-21 17:31:05.123456 utc_now = datetime.now(timezone.utc) print(utc_now) # Timezone-aware UTC time # 2. String formatting formatted = now.strftime("%d %B %Y, %I:%M %p") print(formatted) # 21 April 2026, 05:31 PM # 3. Parse a string to datetime pynfinity_launch = datetime.strptime("2024-01-15", "%Y-%m-%d") print(pynfinity_launch.year) # 2024 # 4. Arithmetic โ timedelta one_week_later = now + timedelta(days=7) days_since_launch = (now - pynfinity_launch).days print(f"Pynfinity has been running for {days_since_launch} days!") # 5. Date comparison expiry = date(2026, 12, 31) today = date.today() premium_active = today < expiry print(f"Premium active: {premium_active}") # 6. Timestamp โ datetime conversion import time ts = time.time() dt = datetime.fromtimestamp(ts) print(dt)
| Concept | Key Takeaway |
|---|---|
| %Y-%m-%d | ISO format: 2026-04-21 |
| %d/%m/%Y | Indian format: 21/04/2026 |
| %I:%M %p | 12-hour time: 05:31 PM |
| timedelta(hours=N) | Add/subtract hours from a datetime |
| .timestamp() | Convert datetime to Unix timestamp float |
Keep exploring and happy coding! ๐