Python strptime()

1. What is strptime()

strptime() converts a date/time string into a datetime object using a specified format pattern.

from datetime import datetime

date_string = "2025-11-24"
dt = datetime.strptime(date_string, "%Y-%m-%d")
print(dt)

It enables reliable parsing of user input, file data, and API responses.


2. Parsing Basic Date Format

from datetime import datetime

date_string = "24/11/2025"
parsed = datetime.strptime(date_string, "%d/%m/%Y")
print(parsed)

Ensures correct interpretation of regional date formats.


3. Parsing Date and Time Together

from datetime import datetime

datetime_string = "2025-11-24 18:45:30"
dt = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")
print(dt)

Supports full timestamp reconstruction.


4. Parsing with Month and Day Names

Handles human-readable date representations.


5. Parsing 12-Hour Clock Format

Supports AM/PM based time parsing.


6. Using strptime() for File Data Processing

Common pattern for log parsing in backend systems.


7. Handling Incorrect Format Errors

Raises ValueError when format does not match.


8. Converting User Input Safely

Ensures safe user input validation.


9. Combining strptime() and strftime()

Transforms one date format into another.


10. Enterprise Use Case: API Timestamp Parsing

Critical for normalizing and processing structured time data.


Common strptime() Format Codes

Code
Description
Example

%Y

Full year

2025

%y

Two-digit year

25

%m

Month (01-12)

11

%d

Day (01-31)

24

%H

Hour (24-hour)

18

%I

Hour (12-hour)

06

%M

Minute

45

%S

Second

30

%p

AM/PM

PM

%A

Full weekday

Monday

%B

Full month

November


Summary

strptime() is essential for:

  • Parsing date strings

  • Validating time input

  • Processing log files

  • Normalizing API timestamps

  • Converting human-readable dates into objects

It forms the foundation for any time-based logic, scheduling, or analytics pipeline.


Last updated