Skip to main content
Python for Beginners
CHAPTER 22 Beginner

Working with Dates and Time

Updated: May 17, 2026
15 min read

# Working with Dates and Time

Welcome to Chapter 22! Date and time operations are essential for logging, scheduling, data analysis, and nearly every real-world application.

---

1. Learning Objectives

  • Use the datetime module for dates and times.
  • Format and parse dates.
  • Perform date arithmetic.
  • Work with timezones.

---

2. The datetime Module

```python id="py22_ex1" from datetime import datetime, date, time, timedelta

# Current date and time now = datetime.now() print(f"Now: {now}") print(f"Date: {now.date()}") print(f"Time: {now.time()}") print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}") print(f"Hour: {now.hour}, Minute: {now.minute}")

# Today's date today = date.today() print(f"Today: {today}")

# Create specific date/time birthday = datetime(1995, 6, 15, 14, 30) print(f"Birthday: {birthday}")

1234
---

## 3. Formatting Dates (strftime)

python id="py22_ex2" now = datetime.now()

print(now.strftime("%Y-%m-%d")) # 2025-01-15 print(now.strftime("%d/%m/%Y")) # 15/01/2025 print(now.strftime("%B %d, %Y")) # January 15, 2025 print(now.strftime("%I:%M %p")) # 02:30 PM print(now.strftime("%A, %B %d, %Y")) # Wednesday, January 15, 2025 print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2025-01-15 14:30:00

1234567891011121314151617
| Code | Meaning | Example |
|------|---------|---------|
| %Y | 4-digit year | 2025 |
| %m | Month (01-12) | 01 |
| %d | Day (01-31) | 15 |
| %H | Hour 24h (00-23) | 14 |
| %I | Hour 12h (01-12) | 02 |
| %M | Minute (00-59) | 30 |
| %S | Second (00-59) | 00 |
| %p | AM/PM | PM |
| %A | Full weekday | Wednesday |
| %B | Full month | January |

---

## 4. Parsing Dates (strptime)

python id="py22ex3" datestr = "2025-06-15" parsed = datetime.strptime(datestr, "%Y-%m-%d") print(f"Parsed: {parsed}")

datestr2 = "June 15, 2025" parsed2 = datetime.strptime(date_str2, "%B %d, %Y") print(f"Parsed: {parsed2}")

1234
---

## 5. Date Arithmetic (timedelta)

python id="py22ex4" from datetime import timedelta

now = datetime.now()

# Add/subtract time tomorrow = now + timedelta(days=1) nextweek = now + timedelta(weeks=1) yesterday = now - timedelta(days=1) twohourslater = now + timedelta(hours=2)

print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}") print(f"Next week: {nextweek.strftime('%Y-%m-%d')}")

# Difference between dates birthday = datetime(2025, 12, 25) diff = birthday - now print(f"Days until Christmas: {diff.days}")

# Age calculator birthdate = datetime(1995, 6, 15) age = (now - birth_date).days // 365 print(f"Age: {age} years")

123456
---

## 6. Practical Examples

### Countdown Timer

python id="py22_ex5" target = datetime(2025, 12, 31, 23, 59, 59) now = datetime.now() remaining = target - now

days = remaining.days hours = remaining.seconds // 3600 minutes = (remaining.seconds % 3600) // 60

print(f"New Year Countdown: {days}d {hours}h {minutes}m")

12
### Timestamp Logger

python id="py22ex6" import time

def log(message): timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(f"[{timestamp}] {message}")

log("Application started") log("Processing data...") log("Task completed") ``

---

7. MCQs with Answers

Q1: datetime.now() returns: A) Date only B) Time only C) Date and time D) Timestamp Answer: C

Q2: strftime is for: A) Parsing B) Formatting C) Creating D) Deleting Answer: B — String Format Time.

Q3: strptime is for: A) Formatting B) Parsing strings to datetime C) Printing D) Sleeping Answer: B — String Parse Time.

Q4: timedelta(days=7) represents: A) 7 hours B) 7 minutes C) 7 days D) 7 seconds Answer: C

Q5: %Y format code gives: A) 2-digit year B) 4-digit year C) Month D) Day Answer: B

Q6: %I vs %H: A) Same B) %I is 12h, %H is 24h C) %I is 24h, %H is 12h D) Neither Answer: B

Q7: To get today's date only: A) datetime.now() B) date.today() C) time.now() D) today() Answer: B

Q8: Subtracting two datetimes gives: A) datetime B) timedelta C) int D) float Answer: B

Q9: %A format gives: A) Abbreviated day B) Full weekday name C) Month D) Year Answer: B

Q10: time.sleep(2) does: A) Formats time B) Pauses for 2 seconds C) Gets time D) Creates timer Answer: B

---

8. Interview Questions

  1. 1. strftime vs strptime? strftime formats datetime→string. strptime parses string→datetime.
  1. 2. How to calculate age from birthdate? (datetime.now() - birthdate).days // 365.
  1. 3. How to handle timezones? Use pytz library or datetime.timezone (Python 3.9+ has zoneinfo).
  1. 4. What is a Unix timestamp? Seconds since January 1, 1970 (epoch). Get with time.time().
  1. 5. How to make datetime timezone-aware? datetime.now(timezone.utc) or use pytz.

---

9. Summary

  • datetime handles both dates and times.
  • strftime() formats datetime to string.
  • strptime() parses string to datetime.
  • timedelta represents duration for date arithmetic.
  • Use time.time()` for Unix timestamps.

---

10. Next Chapter Recommendation

In Chapter 23: Python Regular Expressions, you'll master pattern matching for text processing! 🚀

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·