Python

Working with Dates & Time

Master date and time operations in Python. Learn datetime, timedelta, formatting, and timezone handling.

By TechCoder TeamLast updated: 2026-06-02
In a Nutshell

Master date and time operations in Python. Learn datetime, timedelta, formatting, and timezone handling. This hands-on tutorial focuses on practical implementation of working with dates & time concepts.

Working with Dates & Time

Python's datetime module provides powerful tools for working with dates and times.

The datetime Module

The datetime module is the standard way to work with dates in Python. It provides three main classes:

  • date: Stores year, month, and day.
  • time: Stores hour, minute, second, microsecond.
  • datetime: Stores both date and time components.

Example

from datetime import datetime

now = datetime.now()
print(now)  # Output: 2024-03-15 14:30:00.123456
PYTHON PLAYGROUND
⏳ Loading editor…

Date Arithmetic with timedelta

Often you need to calculate future or past dates (e.g., "7 days from now"). The timedelta class represents a duration or difference between two dates.

Example

from datetime import datetime, timedelta

today = datetime.now()
tomorrow = today + timedelta(days=1)
PYTHON PLAYGROUND
⏳ Loading editor…

Formatting Dates: strftime

Definition: strftime (String Format Time) converts a datetime object into a readable string using format codes.

CodeDescriptionExample
%YYear (4 digits)2024
%mMonth (01–12)12
%dDay (01–31)25
%HHour (00–23)14
%MMinute (00–59)30

Example

now = datetime.now()
print(now.strftime("%Y-%m-%d")) # Output: 2024-12-25
PYTHON PLAYGROUND
⏳ Loading editor…

Parsing Dates: strptime

Definition: strptime (String Parse Time) does the opposite of strftime. It converts a string into a datetime object.

You must provide the format string that matches the structure of your date string.

Example

date_string = "25/12/2024"
date_obj = datetime.strptime(date_string, "%d/%m/%Y")
PYTHON PLAYGROUND
⏳ Loading editor…

Coding Challenge: Age Calculator

PYTHON PLAYGROUND
⏳ Loading editor…

AI Mentor

Confused about "Python datetime timedelta date formatting"? Ask our AI mentor for a simplified explanation.

Quiz

Quiz

Question 1 of 3

Which module handles dates and times?

time
datetime
calendar
date

Key Takeaways

datetime.now() gets current date and time.
timedelta for date arithmetic (add/subtract).
strftime formats datetime as string.
strptime parses string to datetime.

Keep coding! 🚀