π°οΈ Python Date and Time: Your Time Travel Toolkit
Imagine you have a magical watch that can remember any moment, jump forward or backward in time, and even understand what time it is anywhere in the world. Thatβs exactly what Pythonβs datetime module gives you!
π― The Big Picture
Think of dates and times like LEGO blocks:
- Date = A calendar page (year, month, day)
- Time = A clock face (hour, minute, second)
- DateTime = Both together - a complete moment in time!
from datetime import date, time, datetime
π Creating Dates and Times
Making a Date (Like Picking a Calendar Page)
Remember your birthday? Letβs tell Python about it:
from datetime import date
# Create a specific date
my_birthday = date(2020, 5, 15)
# Year=2020, Month=5, Day=15
print(my_birthday) # 2020-05-15
What Day Is Today?
from datetime import date
today = date.today()
print(today) # Shows today's date!
# Get the pieces
print(today.year) # 2024
print(today.month) # 12
print(today.day) # 1
Making a Time (Like Setting an Alarm)
from datetime import time
# Wake up time: 7:30 AM
wake_up = time(7, 30, 0)
# Hour=7, Minute=30, Second=0
print(wake_up) # 07:30:00
DateTime: The Complete Package
from datetime import datetime
# A specific moment
party_time = datetime(2024, 12, 25, 18, 30)
# Christmas Day at 6:30 PM
print(party_time) # 2024-12-25 18:30:00
# Right now!
now = datetime.now()
print(now) # Current date AND time
π¨ Date and Time Formatting
Your dates are like clay - you can shape them however you want!
The Magic of strftime()
strftime = βstring from timeβ (turn time into readable text)
from datetime import datetime
now = datetime.now()
# Different styles
print(now.strftime("%B %d, %Y"))
# December 01, 2024
print(now.strftime("%m/%d/%y"))
# 12/01/24
print(now.strftime("%A"))
# Sunday
π€ Format Code Cheat Sheet
| Code | Meaning | Example |
|---|---|---|
%Y |
Full year | 2024 |
%y |
Short year | 24 |
%m |
Month number | 12 |
%B |
Month name | December |
%d |
Day | 01 |
%A |
Weekday name | Sunday |
%H |
Hour (24h) | 18 |
%I |
Hour (12h) | 06 |
%M |
Minutes | 30 |
%S |
Seconds | 45 |
%p |
AM/PM | PM |
Real Examples
from datetime import datetime
dt = datetime(2024, 7, 4, 14, 30)
# American style
print(dt.strftime("%m/%d/%Y"))
# 07/04/2024
# European style
print(dt.strftime("%d-%m-%Y"))
# 04-07-2024
# Friendly format
print(dt.strftime("%B %d at %I:%M %p"))
# July 04 at 02:30 PM
π Parsing Date Strings
Sometimes dates come as text. We need to turn them back into real dates!
The Magic of strptime()
strptime = βstring parse timeβ (read time from text)
from datetime import datetime
# Text becomes a real datetime!
text = "2024-12-25"
christmas = datetime.strptime(text, "%Y-%m-%d")
print(christmas) # 2024-12-25 00:00:00
print(type(christmas)) # <class 'datetime.datetime'>
Different Text Formats
from datetime import datetime
# American format
date1 = datetime.strptime(
"12/25/2024",
"%m/%d/%Y"
)
# With time
date2 = datetime.strptime(
"Dec 25, 2024 3:30 PM",
"%b %d, %Y %I:%M %p"
)
# European format
date3 = datetime.strptime(
"25-12-2024",
"%d-%m-%Y"
)
β οΈ Watch Out!
The format string MUST match the text exactly:
# This works
datetime.strptime("2024-12-25", "%Y-%m-%d")
# This CRASHES - wrong format!
# datetime.strptime("2024-12-25", "%m/%d/%Y")
β±οΈ timedelta: Time Math Magic
What if you could add or subtract time like numbers?
What is timedelta?
timedelta = a chunk of time you can add or remove
from datetime import timedelta
# Create time chunks
one_day = timedelta(days=1)
one_week = timedelta(weeks=1)
two_hours = timedelta(hours=2)
Adding Time (Into the Future!)
from datetime import datetime, timedelta
today = datetime.now()
# One week from now
next_week = today + timedelta(weeks=1)
# 3 days and 5 hours later
later = today + timedelta(days=3, hours=5)
print(f"Today: {today}")
print(f"Next week: {next_week}")
Subtracting Time (Back to the Past!)
from datetime import datetime, timedelta
today = datetime.now()
# One week ago
last_week = today - timedelta(weeks=1)
# Yesterday
yesterday = today - timedelta(days=1)
print(f"Yesterday: {yesterday}")
Finding the Gap Between Dates
from datetime import date
birthday = date(2024, 5, 15)
today = date(2024, 12, 1)
# Subtract to get timedelta
gap = today - birthday
print(gap.days) # 200 days!
print(gap) # 200 days, 0:00:00
π― Real-World Example: Age Calculator
from datetime import date
def days_until_birthday(birth_month, birth_day):
today = date.today()
next_bday = date(today.year, birth_month, birth_day)
if next_bday < today:
next_bday = date(today.year + 1, birth_month, birth_day)
days_left = (next_bday - today).days
return days_left
print(days_until_birthday(5, 15))
# Days until May 15!
π Timezone Handling
Itβs 3 PM in New York but 8 PM in London. How do we handle this?
The Problem: Naive vs Aware
graph TD A["datetime"] --> B["Naive"] A --> C["Aware"] B --> D["No timezone info"] B --> E["Like a clock with no location"] C --> F["Has timezone info"] C --> G["Knows where in the world"]
Using timezone (Built-in)
from datetime import datetime, timezone, timedelta
# UTC = Universal Time (London in winter)
utc_now = datetime.now(timezone.utc)
print(utc_now)
# Create a timezone offset
# New York is UTC-5
ny_tz = timezone(timedelta(hours=-5))
ny_time = datetime.now(ny_tz)
print(ny_time)
The Better Way: zoneinfo (Python 3.9+)
from datetime import datetime
from zoneinfo import ZoneInfo
# Create timezone-aware times
ny = ZoneInfo("America/New_York")
tokyo = ZoneInfo("Asia/Tokyo")
now_ny = datetime.now(ny)
now_tokyo = datetime.now(tokyo)
print(f"New York: {now_ny}")
print(f"Tokyo: {now_tokyo}")
Converting Between Timezones
from datetime import datetime
from zoneinfo import ZoneInfo
# Start with New York time
ny_tz = ZoneInfo("America/New_York")
ny_time = datetime(2024, 12, 1, 9, 0, tzinfo=ny_tz)
# Convert to Tokyo time
tokyo_tz = ZoneInfo("Asia/Tokyo")
tokyo_time = ny_time.astimezone(tokyo_tz)
print(f"NY: {ny_time}")
# NY: 2024-12-01 09:00:00-05:00
print(f"Tokyo: {tokyo_time}")
# Tokyo: 2024-12-01 23:00:00+09:00
Making Naive Datetime Aware
from datetime import datetime
from zoneinfo import ZoneInfo
# Naive (no timezone)
naive = datetime(2024, 12, 1, 12, 0)
# Add timezone info
london = ZoneInfo("Europe/London")
aware = naive.replace(tzinfo=london)
print(aware)
# 2024-12-01 12:00:00+00:00
π Quick Reference
from datetime import date, time, datetime, timedelta, timezone
from zoneinfo import ZoneInfo # Python 3.9+
# CREATE
today = date.today()
now = datetime.now()
specific = datetime(2024, 12, 25, 18, 30)
# FORMAT (datetime β string)
now.strftime("%Y-%m-%d")
# PARSE (string β datetime)
datetime.strptime("2024-12-25", "%Y-%m-%d")
# TIME MATH
future = now + timedelta(days=7)
past = now - timedelta(hours=3)
gap = date2 - date1 # Returns timedelta
# TIMEZONES
utc_time = datetime.now(timezone.utc)
aware = now.replace(tzinfo=ZoneInfo("UTC"))
converted = aware.astimezone(ZoneInfo("Asia/Tokyo"))
π You Did It!
You now have a time machine in your pocket! You can:
- β Create any date or time you need
- β Format dates in any style
- β Read dates from text
- β Do math with time (add, subtract, compare)
- β Handle timezones like a pro
Remember: Dates are just numbers wearing fancy clothes. Once you understand the pattern, you can style them however you want! πβ¨
