Introduction

The Python datetime module provides useful functionalities to work with Date, Time and DateTime objects. The datetime.strptime() method in particular, allows us to convert datetime string representations into datetime objects that we can use in our programs. Understanding how to use this method is important for working with date and time data in Python. In this tutorial, we will cover the basics of Python datetime module, explain how to use strptime() method, and provide practical examples to help you master this skill.

Table of Contents :

  • How to Convert String to Datetime Object
  • How strptime() Works
  • Format Code List
  • ValueError in strptime

How to convert string to datetime object

  • Python's  datetime.strptime()  function is a handy way to convert a string representation of a date and time into a  datetime.datetime  object. 
  • The function takes two arguments: 
    • The first argument is the string to be parsed. 
    • The second argument is the format string. 
  • The format string in second argument defines how the first argument should be parsed. 
  • The string to be parsed must match the format string exactly. Otherwise, an error will be thrown.
  • It uses the same format as the Python datetime.strftime() function
  •  datetime.strptime()  is a very flexible function. It can handle a variety of date and time formats. 
  • Here are some examples : 

from datetime import datetime

dt_str = datetime.strptime('2018-06-01', '%Y-%m-%d')
print(dt_str)

dt_str = datetime.strptime('Jun 1 2018 1:33PM', '%b %d %Y %I:%M%p')
print(dt_str)


# Output
# 2018-06-01 00:00:00
# 2018-06-01 13:33:00



How strptime() Works:

  •  strptime()  takes two arguments:
    • The first argument is the string to be parsed.
    • The second argument is the format string that specifies the format of the input string.
  • The format string contains format codes that correspond to different parts of the input string.
  •  strptime()  reads the input string and extracts the date and time parts according to the format string.
  • Sample Code :

import datetime

# Parse the input string according to the format string
input_str = "2021-09-22 10:30:00"
dt = datetime.datetime.strptime(input_str, "%Y-%m-%d %H:%M:%S")

# Print the datetime object
print("Datetime object : ", dt)
print("Data Type of dt : ", type(dt))

# Output
# Datetime object :  2021-09-22 10:30:00
# Data Type of dt :  <class 'datetime.datetime'>



Format Code List in tabular form :

CodeMeaning
%aWeekday, abbreviated (Sun, Mon, Tue, etc.)
%AWeekday, full (Sunday, Monday, Tuesday, etc.)
%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday
%dDay of the month, zero-padded (01, 02, ..., 31)
%bMonth name, abbreviated (Jan, Feb, Mar, etc.)
%BMonth name, full (January, February, March, etc.)
%mMonth as a decimal number, zero-padded (01, 02, ..., 12)
%yYear without century, zero-padded (00, 01, ..., 99)
%YYear with century, as a decimal number
%HHour in 24-hour format, zero-padded (00, 01, ..., 23)
%IHour in 12-hour format, zero-padded (01, 02, ..., 12)
 %p AM/PM
%MMinute, zero-padded (00, 01, ..., 59)
%SSecond, zero-padded (00, 01, ..., 59)
%fMicrosecond, zero-padded (000000, 000001, ..., 999999)
%zUTC offset in the form +HHMM or -HHMM 
%Ztime zone name %j - day of the year as a zero-padded decimal number (001-366) 
%Uweek number of the year (Sunday as the first day of the week) as a zero padded decimal number (00-53) 
%Wweek number of the year (Monday as the first day of the week) as a decimal number (00-53)
%clocale's appropriate date and time representation 
%xlocale's appropriate date representation 
%Xlocale's appropriate time representation 
%%a literal '%' character 

ValueError in strptime:

  • If the input string does not match the format string,  strptime()  raises a ValueError.
  •  ValueError : time data 'INVALID_STRING' does not match format '%Y-%m-%d' 
  • Example :

import datetime

# This will raise a ValueError
input_str = "2021/09/22"
dt = datetime.datetime.strptime(input_str, "%Y-%m-%d")


# Output
# ValueError: time data '2021/09/22' does not match format '%Y-%m-%d'


 

Prev. Tutorial : Using datetime.strftime()

Next Tutorial : dates and time