Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> Python

Master Python's strptime() for Accurate Date Parsing

Python strptime(): Converting Strings to Datetime Objects

This guide shows how to create datetime objects from strings using Python's datetime.strptime() method, with practical examples and a comprehensive format code reference.

Video: Dates and Times in Python

Watch the official Python tutorial to deepen your understanding of datetime handling.

The strptime() method creates a datetime object from a string that follows a specified format.

Note: Not every string can be parsed; the input must match the format code exactly.


Example 1: Converting a Simple Date String

from datetime import datetime

date_string = "21 June, 2018"

print("date_string =", date_string)
print("type of date_string =", type(date_string))

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

print("date_object =", date_object)
print("type of date_object =", type(date_object))

When you run the program, the output will be:

date_string = 21 June, 2018
type of date_string = <class 'str'>
date_object = 2018-06-21 00:00:00
type of date_object = <class 'datetime.datetime'>

How strptime() Works

The strptime() class method accepts two arguments:

Based on these inputs, the method returns a datetime object that represents the same moment in time.

In the example above, the format code %d %B, %Y means:


Example 2: Parsing Ambiguous Dates

from datetime import datetime

dt_string = "12/11/2018 09:15:32"

# Assuming day/month/year format
dt_object1 = datetime.strptime(dt_string, "%d/%m/%Y %H:%M:%S")
print("dt_object1 =", dt_object1)

# Assuming month/day/year format
dt_object2 = datetime.strptime(dt_string, "%m/%d/%Y %H:%M:%S")
print("dt_object2 =", dt_object2)

The program produces:

dt_object1 = 2018-11-12 09:15:32
dt_object2 = 2018-12-11 09:15:32

Complete List of Format Codes

The table below summarizes all directives you can use with strptime(). For full documentation, refer to Python’s official datetime module guide.

Directive Meaning Example
%aAbbreviated weekday name.Sun, Mon, ...
%AFull weekday name.Sunday, Monday, ...
%wWeekday as a decimal number.0, 1, ..., 6
%dDay of month (zero‑padded).01, 02, ..., 31
%-dDay of month (no padding).1, 2, ..., 30
%bAbbreviated month name.Jan, Feb, ..., Dec
%BFull month name.January, February, ...
%mMonth number (zero‑padded).01, 02, ..., 12
%-mMonth number (no padding).1, 2, ..., 12
%yYear without century (zero‑padded).00, 01, ..., 99
%-yYear without century (no padding).0, 1, ..., 99
%YYear with century.2013, 2019, ...
%HHour (24‑hour clock, zero‑padded).00, 01, ..., 23
%-HHour (24‑hour clock, no padding).0, 1, ..., 23
%IHour (12‑hour clock, zero‑padded).01, 02, ..., 12
%-IHour (12‑hour clock, no padding).1, 2, ..., 12
%pLocale’s AM or PM.AM, PM
%MMinute (zero‑padded).00, 01, ..., 59
%-MMinute (no padding).0, 1, ..., 59
%SSecond (zero‑padded).00, 01, ..., 59
%-SSecond (no padding).0, 1, ..., 59
%fMicrosecond (zero‑padded).000000 – 999999
%zUTC offset (+HHMM or –HHMM).
%ZTime‑zone name.
%jDay of year (zero‑padded).001, 002, ..., 366
%-jDay of year (no padding).1, 2, ..., 366
%UWeek number (Sunday first).00, 01, ..., 53
%WWeek number (Monday first).00, 01, ..., 53
%cLocale’s date & time.Mon Sep 30 07:06:05 2013
%xLocale’s date.09/30/13
%XLocale’s time.07:06:05
%%A literal percent sign.%

Common Error: ValueError

If the string and format code do not match, strptime() raises a ValueError. For example:

from datetime import datetime

date_string = "12/11/2018"
# Incorrect format – expects day month year
date_object = datetime.strptime(date_string, "%d %m %Y")
print("date_object =", date_object)

Running this code produces:

ValueError: time data '12/11/2018' does not match format '%d %m %Y'

Recommended Reading: Python strftime()

Python

  1. Python Keywords and Identifiers: Mastering Reserved Words and Naming Conventions
  2. Mastering Python Data Types: A Practical Guide
  3. Mastering Python Operators: A Comprehensive Guide
  4. Mastering Python's While Loop: Syntax, Examples, and Best Practices
  5. Python List Operations: Creation, Access, Modification, and Advanced Techniques
  6. Mastering Python Tuples: Creation, Access, and Advanced Operations
  7. Mastering Python Dictionaries: Creation, Manipulation, and Advanced Techniques
  8. Python Regular Expressions (re Module) – A Practical Guide
  9. Mastering Python's strftime(): Convert Dates and Times to Readable Strings
  10. Mastering Python’s time Module: Functions, Structs, and Practical Examples