Labs ICT
โญ Pro Login

Datetime

1 min read | Python Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Current Date and Time

datetime.now() returns the current local date and time. Access individual components like year, month, day, hour, minute, second.

from datetime import datetime

now = datetime.now()
print(now)
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")

Using timedelta

timedelta represents a duration. Add or subtract it from a datetime to get future or past dates.

from datetime import datetime, timedelta

today = datetime.now()
tomorrow = today + timedelta(days=1)
last_week = today - timedelta(weeks=1)
print("Tomorrow:", tomorrow)
print("Last week:", last_week)

Formatting Dates with strftime

strftime() formats a datetime into a string. Common codes: %Y (year), %m (month), %d (day), %H (hour), %M (minute).

from datetime import datetime

now = datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)

friendly = now.strftime("%B %d, %Y at %I:%M %p")
print(friendly)

๐Ÿงช Quick Quiz

Which module is used for dates and times in Python?