What is Computer

Module: M2-R5: Web Design & Publishing

Chapter: Ch1 Computer Intro

🔹 Introduction to Date & Time Functions

Python provides the datetime module to work with dates and times, including formatting, arithmetic, and conversions.

🔹 Date & Time Functions with Examples
🔹 datetime.now()

Returns current local date and time.

from datetime import datetime
now = datetime.now()
print(now)

Output:

2025-10-19 20:45:30.123456 (varies)
🔹 datetime.today()

Returns current local date without time info.

from datetime import datetime
today = datetime.today()
print(today)

Output:

2025-10-19 20:45:30.123456 (varies)
🔹 datetime.date()

Creates a date object (year, month, day).

from datetime import date
my_date = date(2025, 10, 19)
print(my_date)

Output:

2025-10-19
🔹 datetime.time()

Creates a time object (hour, minute, second).

from datetime import time
my_time = time(14, 30, 45)
print(my_time)

Output:

14:30:45
🔹 timedelta

Represents a duration, used for date arithmetic.

from datetime import datetime, timedelta
now = datetime.now()
future = now + timedelta(days=5)
print(future)

Output:

2025-10-24 20:45:30.123456 (varies)
🔹 strftime('%Y-%m-%d')

Formats date as YYYY-MM-DD.

from datetime import datetime
now = datetime.now()
print(now.strftime('%Y-%m-%d'))

Output:

2025-10-19
🔹 strftime('%d/%m/%Y')

Formats date as DD/MM/YYYY.

from datetime import datetime
now = datetime.now()
print(now.strftime('%d/%m/%Y'))

Output:

19/10/2025
🔹 strftime('%A, %B %d, %Y')

Formats date with full weekday and month names.

from datetime import datetime
now = datetime.now()
print(now.strftime('%A, %B %d, %Y'))

Output:

Sunday, October 19, 2025
🔹 strftime('%I:%M %p')

Formats time in 12-hour format with AM/PM.

from datetime import datetime
now = datetime.now()
print(now.strftime('%I:%M %p'))

Output:

08:45 PM
🔹 strftime('%H:%M:%S')

Formats time in 24-hour format.

from datetime import datetime
now = datetime.now()
print(now.strftime('%H:%M:%S'))

Output:

20:45:30
🔹 strftime('%a, %d %b %Y')

Short weekday, day, short month, year.

from datetime import datetime
now = datetime.now()
print(now.strftime('%a, %d %b %Y'))

Output:

Sun, 19 Oct 2025
🔹 strftime('%j')

Day of the year (001-366).

from datetime import datetime
now = datetime.now()
print(now.strftime('%j'))

Output:

292
🔹 strftime('%U')

Week number of the year (Sunday as first day).

from datetime import datetime
now = datetime.now()
print(now.strftime('%U'))

Output:

42
✅ Summary
  • Python datetime module is used for all date and time operations.
  • timedelta allows adding/subtracting time durations.
  • strftime is used to format dates and times in custom ways.
  • Functions can be combined to manipulate, display, and calculate date/time efficiently.
Quick Links