Python datetime Module

Ka Kavitha V Updated 03 Oct 2026
7 min read

Datetime Module

Dates and times appear in almost every real application: order timestamps, due dates, log entries, booking systems, and birthdays. Python does not have a built-in "date" data type like int or str. Instead, it provides the datetime module in the standard library, which offers dedicated objects for working with dates, times, and time differences.

Importing the datetime Module

The datetime module contains several classes. The most commonly used ones are:

ClassRepresentsExample
datetimeA date and a time2025-11-15 18:45:30
dateA date only2025-11-15
timeA time only18:45:30
timedeltaA duration or difference between two dates/times3 days, 4 hours

Notice that the module and its main class share the same name, datetime. There are two common ways to import it:

import datetime
now = datetime.datetime.now()   # module.class.method
from datetime import datetime
now = datetime.now()            # class.method

This lesson uses the second form, which is shorter.

Getting the Current Date and Time

datetime.now() returns the current local date and time.

from datetime import datetime

current_time = datetime.now()
print("Current date and time:", current_time)

Example output (your value will differ):

Current date and time: 2026-01-29 16:02:14.532891

The output contains these parts, in order:

PartValue in the Example
Year2026
Month01
Day29
Hour (24-hour clock)16
Minute02
Second14
Microsecond532891

Extracting Date Components

A datetime object gives direct access to each component through attributes.

from datetime import datetime

today = datetime.now()

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
print("Weekday:", today.strftime("%A"))

Example output:

Year: 2026
Month: 1
Day: 29
Weekday: Thursday
  • year, month, day, hour, minute, second, and microsecond return integers.
  • strftime("%A") returns the full weekday name as a string. (strftime() is explained below.)

Creating Custom Date Objects

Use the datetime() constructor to create a specific date and time.

Parameters

RequiredOptional (default)
yearhour (0)
monthminute (0)
daysecond (0)
microsecond (0)
tzinfo — time zone information (None)

Example: A Specific Date

from datetime import datetime

event_date = datetime(2024, 12, 25)
print("Event date:", event_date)

Expected output:

Event date: 2024-12-25 00:00:00

When time values are not provided, they default to midnight, 00:00:00.

Example: A Date With a Time

from datetime import datetime

meeting = datetime(2025, 3, 10, 14, 30)
print("Meeting scheduled at:", meeting)

Expected output:

Meeting scheduled at: 2025-03-10 14:30:00

Python validates the values. An impossible date such as datetime(2025, 2, 30) raises ValueError: day is out of range for month.

Formatting Dates With strftime()

The strftime() method ("string format time") converts a datetime object into a human-readable string, using format codes that start with %.

Example: Display the Month Name

from datetime import datetime

sample_date = datetime(2023, 11, 15)
formatted = sample_date.strftime("%B")
print("Month:", formatted)

Expected output:

Month: November

Common strftime() Format Codes

The examples in this table use the date and time Saturday, 15 November 2025, 18:45:30.123456.

CodeMeaningExample
%aWeekday (short)Sat
%AWeekday (full)Saturday
%dDay of the month (01–31)15
%bMonth name (short)Nov
%BMonth name (full)November
%mMonth number (01–12)11
%yYear (2 digits)25
%YYear (4 digits)2025
%HHour, 24-hour clock (00–23)18
%IHour, 12-hour clock (01–12)06
%pAM / PMPM
%MMinute (00–59)45
%SSecond (00–59)30
%fMicrosecond123456
%jDay of the year (001–366)319
%UWeek number, Sunday as the first day of the week45
%WWeek number, Monday as the first day of the week45
%cLocale's full date and timeSat Nov 15 18:45:30 2025
%xLocale's date11/15/25
%XLocale's time18:45:30
%%A literal % symbol%

Note: The output of %a, %A, %b, %B, %c, %x, and %X depends on your system's locale (language and region settings). The values shown are for the default English/US locale. Also note that %M is minutes, while %m is the month — a very common mix-up.

strftime() Format Codes: Complete Examples

All of the following examples use this datetime object:

from datetime import datetime

dt = datetime(2025, 11, 15, 18, 45, 30, 123456)

15 November 2025 falls on a Saturday.

Weekday Formats

print(dt.strftime("%a"))
print(dt.strftime("%A"))

Expected output:

Sat
Saturday
  • %a → short weekday name
  • %A → full weekday name

Day of the Month

print(dt.strftime("%d"))

Expected output:

15

%d always uses two digits, so the 5th of a month appears as 05.

Month Formats

print(dt.strftime("%b"))
print(dt.strftime("%B"))
print(dt.strftime("%m"))

Expected output:

Nov
November
11
  • %b → short month name
  • %B → full month name
  • %m → month number

Year Formats

print(dt.strftime("%y"))
print(dt.strftime("%Y"))

Expected output:

25
2025
  • %y → year with 2 digits
  • %Y → year with 4 digits

Hour Formats

print(dt.strftime("%H"))
print(dt.strftime("%I"))
print(dt.strftime("%p"))

Expected output:

18
06
PM
  • %H → hour on the 24-hour clock
  • %I → hour on the 12-hour clock
  • %p → AM or PM; usually combined with %I

Minute, Second, and Microsecond

print(dt.strftime("%M"))
print(dt.strftime("%S"))
print(dt.strftime("%f"))

Expected output:

45
30
123456

Day and Week Information

print(dt.strftime("%j"))
print(dt.strftime("%U"))
print(dt.strftime("%W"))

Expected output:

319
45
45
  • %j → day of the year: 15 November is the 319th day of 2025.
  • %U → week number of the year, counting weeks that start on Sunday.
  • %W → week number of the year, counting weeks that start on Monday.

For both %U and %W, days before the first Sunday (or Monday) of the year are in week 00.

Full Date and Time Formats

print(dt.strftime("%c"))
print(dt.strftime("%x"))
print(dt.strftime("%X"))

Expected output (default English/US locale):

Sat Nov 15 18:45:30 2025
11/15/25
18:45:30
  • %c → the locale's full date and time
  • %x → the locale's date
  • %X → the locale's time

Percent Symbol

print(dt.strftime("%%"))

Expected output:

%

%% prints a literal %, because a single % starts a format code.

Real-World Example: A Readable Timestamp

Format codes can be combined with ordinary text and punctuation:

formatted_date = dt.strftime("%A, %d %B %Y %I:%M %p")
print(formatted_date)

Expected output:

Saturday, 15 November 2025 06:45 PM

Common formats used in applications:

PurposeFormat StringResult
ISO-style date"%Y-%m-%d"2025-11-15
Indian/European date"%d/%m/%Y"15/11/2025
US date"%m/%d/%Y"11/15/2025
File-name timestamp"%Y%m%d_%H%M%S"20251115_184530

Converting Strings to Dates With strptime()

strptime() ("string parse time") does the reverse of strftime(): it reads a string and creates a datetime object. You provide the format that the string follows.

from datetime import datetime

text = "25-12-2026"
christmas = datetime.strptime(text, "%d-%m-%Y")
print(christmas)

Expected output:

2026-12-25 00:00:00

This is essential when dates arrive as text — from user input, CSV files, or APIs. If the string does not match the format, Python raises a ValueError.

MethodDirectionRemember It As
strftime()datetime → stringformat
strptime()string → datetimeparse

Date Arithmetic With timedelta

A timedelta represents a duration. You can add it to or subtract it from dates, and subtracting two dates produces a timedelta.

Adding Days to a Date

from datetime import date, timedelta

order_date = date(2026, 10, 1)
delivery_date = order_date + timedelta(days=30)
print("Delivery by:", delivery_date)

Expected output:

Delivery by: 2026-10-31

Finding the Difference Between Two Dates

from datetime import date

today = date(2026, 10, 1)
new_year_eve = date(2026, 12, 31)

difference = new_year_eve - today
print(difference)
print("Days remaining:", difference.days)

Expected output:

91 days, 0:00:00
Days remaining: 91

The result is a timedelta; its .days attribute gives the number of whole days.

timedelta also accepts weeks, hours, minutes, and seconds, for example timedelta(hours=2, minutes=30).

Common Mistakes

MistakeProblem
import datetime followed by datetime.now()AttributeError — use datetime.datetime.now(), or from datetime import datetime
Confusing %m (month) and %M (minute)Dates show minutes in place of months, or the reverse
Confusing %H (24-hour) and %I (12-hour)Wrong hour shown; pair %I with %p
Using strftime() to read a stringUse strptime() to parse strings into dates
Creating an impossible dateValueError
Comparing a date with a stringTypeError — convert the string with strptime() first
  • Python Modules — importing standard-library modules
  • Python Formatting Strings — f-strings also accept date format codes, such as f"{dt:%d %B %Y}"
  • Python Type Casting — converting between strings and other types

0 Comments

Reviewed before they appear

No comments yet.

Python
Ask about this post
AI Ask about this post

Ask questions about Python datetime Module and get answers drawn from it.

Signed-in readers only.