Python datetime module

Last Updated : 22 Sep, 2026

The datetime module in Python provides classes and methods for working with dates, times, time intervals, and time zones. It is useful for tasks such as scheduling, logging events, calculating date differences, formatting dates, and handling time-based data.

Installation

The datetime module is part of Python's standard library, so it does not require separate installation.

from datetime import datetime

Date class

The date class is used to create and manipulate calendar dates. A date object contains the year, month, and day.

Syntax

class datetime.date(year, month, day)

Parameters:

  • year: Year of the date.
  • month: Month from 1 to 12.
  • day: Valid day for the specified month and year.

Important Notes

  • Passing a value of an invalid type, such as a string instead of an integer, raises a TypeError.
  • Passing a value outside the valid range raises a ValueError.
  • A date object contains only year, month, and day. It does not contain time or timezone information.

Example 1: Creating a Date Object

Python
from datetime import date

d = date(2026, 8, 13)
print(d)

Output
2026-08-13

Explanation:

  • date() creates a date object using year, month, and day.
  • The date is displayed in YYYY-MM-DD format.

Example 2: Get Current Date

Python
from datetime import date
t = date.today()
print(t)

Output
2025-07-26

Explanation:

  • date.today() returns the current local date.
  • The result is stored in the today variable.

Example 3: Access Date Attributes

Python
from datetime import date
t = date.today()
print(t.year)
print(t.month)
print(t.day)

Output
2025
7
26

Explanation:

  • year returns the year.
  • month returns the month.
  • day returns the day.

Example 4: Create Date from Timestamp

Python
from datetime import datetime
date_time = datetime.fromtimestamp(1887639468)
print(date_time)
print(date_time.date())

Output
2029-10-25 16:17:48
2029-10-25

Explanation:

  • datetime.fromtimestamp() converts a POSIX timestamp into a datetime object.
  • date_time contains both the date and time.
  • date_time.date() extracts only the date from the datetime object.
  • The output shows the complete datetime first and the extracted date second.

Example 5: Convert Date to String

Python
from datetime import date
t = date.today()
date_str = t.isoformat()
print(date_str)
print(type(date_str))

Output
2025-07-26
<class 'str'>

Explanation:

  • isoformat() converts the date object into an ISO-formatted string.
  • The returned value has the str data type.

Used Date Methods

Method

Description

today()

Returns the current local date.

isoformat()

Converts a date into YYYY-MM-DD format.

strftime()

Formats a date according to a specified format.

fromisoformat()

Creates a date object from an ISO-formatted string.

replace()

Returns a date with selected values changed.

isoweekday()

Returns the weekday as an integer from 1 to 7.

weekday()

Returns the weekday as an integer from 0 to 6.

Time class

The time class represents a time of day independently of a date. It can contain hour, minute, second, microsecond, and timezone information.

Syntax

time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

Example 1: Create a Time Object

Python
from datetime import time

t = time(13, 24, 56)
print(t)

Output
13:24:56

Explanation:

  • time() creates a time object.
  • The values represent hour, minute, and second.

Example 2: Access Time Attributes

Python
from datetime import time

Time = time(11, 34, 56)
print("hour =", Time.hour)
print("minute =", Time.minute)
print("second =", Time.second)
print("microsecond =", Time.microsecond)

Output
hour = 11
minute = 34
second = 56
microsecond = 0

Explanation:

  • hour returns the hour.
  • minute returns the minute.
  • second returns the second.

Example 3: Convert Time to String

Python
from datetime import time

t = time(12, 24, 36)
result = t.isoformat()

print(result)
print(type(result))

Output
12:24:36
<class 'str'>

Explanation:

  • isoformat() converts the time object into a string.
  • The result follows the ISO time format

List of Time class Methods

Methods

Description

isoformat()Returns the time as an ISO-formatted string.
replace()Returns a time object with selected values changed.
strftime()Formats the time according to a specified format.

fromisoformat()

Creates a time object from an ISO-formatted string.

Datetime class

The datetime class combines date and time information in a single object. It is commonly used when both the date and time of an event need to be stored or processed.

Syntax

datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

Parameters:

  • year: Year of the date.
  • month: Month from 1 to 12.
  • day: Valid day for the specified month and year.
  • hour: Hour from 0 to 23.
  • minute: Minute from 0 to 59.
  • second: Second from 0 to 59.
  • microsecond: Microsecond from 0 to 999999.

Note - Passing an argument other than integer will raise a TypeError and passing arguments outside the range will raise ValueError.

Example 1: Create a Datetime Object

Python
from datetime import datetime

dt = datetime(2026, 8, 13, 10, 30, 45)
print(dt)

Output
2026-08-13 10:30:45

Explanation:

  • datetime() creates an object containing both date and time.
  • The values represent year, month, day, hour, minute, and second.

Example 2: Get Current Date and Time

Python
from datetime import datetime

now = datetime.now()
print(now)

Output
2026-08-13 05:35:28.162136

Explanation:

  • datetime.now() returns the current local date and time.
  • Microseconds may also be included in the result.

Example 3: Access Datetime Attributes

Python
from datetime import datetime

dt = datetime(2026, 8, 13, 10, 30)

print(dt.year)
print(dt.month)
print(dt.hour)
print(dt.minute)

Output
2026
8
10
30

Explanation:

  • year returns the year.
  • month returns the month.
  • hour returns the hour.
  • minute returns the minute.

Example 4: Convert Datetime to String

Python
from datetime import datetime

dt = datetime(2026, 8, 13, 10, 30)
result = dt.isoformat()

print(result)
print(type(result))

Output
2026-08-13T10:30:00
<class 'str'>

Explanation:

  • isoformat() converts the datetime object into an ISO-formatted string.
  • The returned value has the str data type.

Example 5: Format Datetime

Python
from datetime import datetime

dt = datetime(2026, 8, 13, 10, 30)
result = dt.strftime("%d-%m-%Y %H:%M")

print(result)

Output
13-08-2026 10:30

Explanation:

  • strftime() converts a datetime object into a formatted string.
  • %d represents the day.
  • %m represents the month.
  • %Y represents the year.
  • %H represents the hour.
  • %M represents the minute.

Example 6: Convert String to Datetime

Python
from datetime import datetime

date_str = "2026-08-13 10:30"
result = datetime.strptime(date_str, "%Y-%m-%d %H:%M")

print(result)

Output
2026-08-13 10:30:00

Explanation:

  • strptime() converts a formatted string into a datetime object.
  • The format string tells Python how the input string is structured.

Datetime Class Methods

Function Name

Description

now()Returns the current local date and time.

today()

Returns the current local datetime.

strftime()

Converts a datetime object into a formatted string.

fromisoformat()Creates a datetime object from an ISO-formatted string.

timestamp()

Returns the POSIX timestamp.

date()

Returns the date part of a datetime object.

time()

Returns the time part of a datetime object.

isoformat()Returns the datetime in ISO 8601 format.

replace()

Returns a datetime object with selected values changed.

strptime()

Creates a datetime object from a formatted string.

Timedelta Class

The timedelta class represents a duration or difference between dates and times. It can be used to add or subtract days, hours, minutes, and other time units.

Syntax

timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Example 1: Add Days to a Date

The timedelta function demonstration

Python
from datetime import date, timedelta

d = date(2026, 8, 13)
new_date = d + timedelta(days=5)

print(new_date)

Output
2026-08-18

Explanation:

  • timedelta(days=5) represents a duration of five days.
  • Adding it to a date moves the date five days forward.

Example 2: Find Difference Between Dates

Date and Time differences can also be found using this class.

Python
from datetime import date

start = date(2026, 8, 13)
end = date(2026, 8, 20)

difference = end - start

print(difference)

Output
7 days, 0:00:00

Explanation:

  • Subtracting two date objects returns a timedelta object.
  • The result represents the difference between the two dates.

Example 3: Add Hours to Datetime

Python
from datetime import datetime, timedelta

dt = datetime(2026, 8, 13, 10, 30)
new_dt = dt + timedelta(hours=3)

print(new_dt)

Output
2026-08-13 13:30:00

Explanation:

  • timedelta(hours=3) represents three hours.
  • Adding it to the datetime moves the time three hours forward.

Operations with Timedelta

Operator

Description

date + timedeltaAdds a duration to a date.
date - timedeltaSubtracts a duration from a date.
datetime + timedeltaMoves a datetime forward by a duration.
datetime - timedeltaMoves a datetime backward by a duration.
date2 - date1Calculates the difference between two dates.
datetime2 - datetime1Calculates the difference between two datetime objects.

Timezone class

The timezone class represents a fixed offset from UTC. It can be used to create timezone-aware datetime objects.

Syntax

timezone(offset, name=None)

Parameter:

  • offset: A timedelta object representing the UTC offset.
  • name: Optional name for the timezone.

Example: Create a Timezone-Aware Datetime

Python
from datetime import datetime, timezone, timedelta

ist = timezone(timedelta(hours=5, minutes=30), "IST")
dt = datetime(2026, 8, 13, 10, 30, tzinfo=ist)

print(dt)
print(dt.tzname())

Output
2026-08-13 10:30:00+05:30
IST

Explanation:

  • timedelta(hours=5, minutes=30) creates a UTC offset of +05:30.
  • timezone() creates a fixed timezone.
  • tzinfo=ist attaches the timezone to the datetime object.
  • tzname() returns the timezone name
Comment