Lesson 60 of 70 – Python Date and Time
86%

Python Date and Time

Python provides the built-in datetime module for working with dates, times, time differences, and date/time formatting.

The datetime module is commonly used in applications such as attendance systems, booking systems, reports, billing software, scheduling applications, and many other projects.

Note: The datetime module provides classes such as date, time, datetime, and timedelta.
Importing datetime

The datetime module can be imported using:

import datetime

You can then access classes and functions using the module name.

import datetime

today = datetime.date.today()

print(today)
Example Output:
2026-09-20
Today's Date

The date.today() method returns the current local date according to the system clock.

from datetime import date

today = date.today()

print(today)
Example Output:
2026-09-20
Getting Year, Month and Day

The date object provides the year, month, and day attributes.

from datetime import date

today = date.today()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
Example Output:
Year: 2026
Month: 9
Day: 20
Creating a Date

You can create a specific date using date(year, month, day).

from datetime import date

birthday = date(2000, 5, 15)

print(birthday)
Output:
2000-05-15
Current Date and Time

The datetime.now() method returns the current local date and time according to the system clock.

from datetime import datetime

now = datetime.now()

print(now)
Example Output:
2026-09-20 16:30:25.123456

The exact output depends on the date and time when the program runs.

Getting Current Time

The datetime.now() result contains both date and time. You can access the time components using hour, minute, second, and microsecond.

from datetime import datetime

now = datetime.now()

print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
Creating a Time

The time class can be used to represent a time without a date.

from datetime import time

t = time(14, 30, 45)

print(t)
Output:
14:30:45
Time Components
from datetime import time

t = time(14, 30, 45)

print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
Output:
Hour: 14
Minute: 30
Second: 45
Creating a datetime Object

The datetime class can represent both date and time.

from datetime import datetime

dt = datetime(2026, 9, 20, 10, 30, 0)

print(dt)
Output:
2026-09-20 10:30:00
Formatting Date and Time with strftime()

The strftime() method converts a date or datetime object into a formatted string.

from datetime import datetime

now = datetime.now()

formatted = now.strftime("%d-%m-%Y")

print(formatted)
Example Output:
20-09-2026
Common strftime Codes
Code Meaning Example
%Y Four-digit year 2026
%y Two-digit year 26
%m Month as number 09
%d Day of month 20
%H Hour, 24-hour format 16
%I Hour, 12-hour format 04
%M Minute 30
%S Second 25
%p AM or PM PM
Formatting with Date and Time
from datetime import datetime

dt = datetime(2026, 9, 20, 16, 30)

print(dt.strftime("%d/%m/%Y"))
print(dt.strftime("%I:%M %p"))
Output:
20/09/2026
04:30 PM
Converting String to Date with strptime()

The strptime() method converts a string into a datetime object according to a specified format.

from datetime import datetime

date_string = "20-09-2026"

date_object = datetime.strptime(
    date_string,
    "%d-%m-%Y"
)

print(date_object)
Output:
2026-09-20 00:00:00
Date Difference with timedelta

The timedelta class represents a duration or difference between dates and times.

from datetime import date, timedelta

today = date.today()

future_date = today + timedelta(days=10)

print(future_date)
Example:

If today is 2026-09-20, the result will be:

2026-09-30
Subtracting Days
from datetime import date, timedelta

today = date.today()

previous_date = today - timedelta(days=7)

print(previous_date)

Here, seven days are subtracted from the current date.

Adding Hours and Minutes
from datetime import datetime, timedelta

now = datetime.now()

future = now + timedelta(
    hours=2,
    minutes=30
)

print(future)

timedelta can represent days, seconds, microseconds, milliseconds, minutes, hours, and weeks.

Finding Difference Between Dates
from datetime import date

start = date(2026, 9, 1)

end = date(2026, 9, 20)

difference = end - start

print(difference.days)
Output:
19
Comparing Dates

Date objects can be compared using operators such as <, >, ==, and !=.

from datetime import date

date1 = date(2026, 9, 10)

date2 = date(2026, 9, 20)

if date1 < date2:
    print("date1 is earlier")
Output:
date1 is earlier
Getting Day of Week

The weekday() method returns a number representing the day of the week. Monday is 0 and Sunday is 6.

from datetime import date

today = date.today()

print(today.weekday())

The isoweekday() method uses Monday as 1 and Sunday as 7.

Day Name with strftime()

The %A format code returns the full weekday name.

from datetime import date

today = date.today()

print(today.strftime("%A"))
Example Output:
Sunday

The exact result depends on the date when the program runs.

Month Name

The %B format code returns the full month name.

from datetime import date

today = date.today()

print(today.strftime("%B"))
Example Output:
September
ISO Format

The isoformat() method returns a standard ISO-style representation.

from datetime import date

today = date.today()

print(today.isoformat())
Example Output:
2026-09-20
Date and Time Formatting Example
from datetime import datetime

now = datetime.now()

print("Date:", now.strftime("%d-%m-%Y"))
print("Time:", now.strftime("%I:%M:%S %p"))
print("Day:", now.strftime("%A"))
print("Month:", now.strftime("%B"))
Example Output:
Date: 20-09-2026
Time: 04:30:25 PM
Day: Sunday
Month: September
Using datetime.combine()

The combine() method combines a date object and a time object into a datetime object.

from datetime import date, time, datetime

d = date(2026, 9, 20)

t = time(10, 30)

dt = datetime.combine(d, t)

print(dt)
Output:
2026-09-20 10:30:00
Replacing Date or Time Components

Date and datetime objects are immutable, so methods such as replace() create a new object rather than modifying the original.

from datetime import date

old_date = date(2026, 9, 20)

new_date = old_date.replace(
    year=2027
)

print(old_date)
print(new_date)
Output:
2026-09-20
2027-09-20
Timezone-Aware Date and Time

For applications that need reliable timezone handling, Python supports timezone-aware datetime objects. The standard library provides timezone and zoneinfo.

from datetime import datetime, timezone

now = datetime.now(timezone.utc)

print(now)

This creates a timezone-aware datetime representing the current time in UTC.

Using zoneinfo

The zoneinfo module provides access to the system's IANA time zone database when available.

from datetime import datetime
from zoneinfo import ZoneInfo

india_time = datetime.now(
    ZoneInfo("Asia/Kolkata")
)

print(india_time)

This creates a timezone-aware datetime for the Asia/Kolkata time zone.

Useful datetime Classes
Class Purpose
date Represents a calendar date.
time Represents a time of day.
datetime Represents both date and time.
timedelta Represents a duration or difference between dates/times.
timezone Represents a fixed UTC offset.
Real-Life Example – Calculate Age
from datetime import date

birth_date = date(2000, 5, 15)

today = date.today()

age = today.year - birth_date.year

if (today.month, today.day) < (
    birth_date.month,
    birth_date.day
):
    age -= 1

print("Age:", age)

This example calculates age by comparing the birthday with today's date.

Real-Life Example – Due Date
from datetime import date, timedelta

start_date = date.today()

due_date = start_date + timedelta(days=30)

print("Start Date:", start_date)
print("Due Date:", due_date)

This type of calculation can be useful for subscriptions, assignments, bills, bookings, and payment due dates.

Key Points
  • Python provides the built-in datetime module for date and time operations.
  • date represents a calendar date.
  • time represents a time of day.
  • datetime represents both date and time.
  • timedelta represents a duration or difference.
  • date.today() returns the current local date according to the system clock.
  • datetime.now() returns the current local date and time.
  • strftime() converts date/time objects into formatted strings.
  • strptime() converts a string into a datetime object.
  • weekday() returns the weekday number from 0 to 6.
  • zoneinfo can be used for named time zones.
  • Date and time handling is useful in reports, attendance, bookings, payments, and scheduling systems.

🧠 Quick Quiz

Question: Which method is used to format a datetime object into a string?