Beginner Level
Intermediate Level
Advanced Level
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 adatetime.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 :
Code | Meaning |
---|---|
%a | Weekday, abbreviated (Sun, Mon, Tue, etc.) |
%A | Weekday, full (Sunday, Monday, Tuesday, etc.) |
%w | Weekday as a decimal number, where 0 is Sunday and 6 is Saturday |
%d | Day of the month, zero-padded (01, 02, ..., 31) |
%b | Month name, abbreviated (Jan, Feb, Mar, etc.) |
%B | Month name, full (January, February, March, etc.) |
%m | Month as a decimal number, zero-padded (01, 02, ..., 12) |
%y | Year without century, zero-padded (00, 01, ..., 99) |
%Y | Year with century, as a decimal number |
%H | Hour in 24-hour format, zero-padded (00, 01, ..., 23) |
%I | Hour in 12-hour format, zero-padded (01, 02, ..., 12) |
%p | AM/PM |
%M | Minute, zero-padded (00, 01, ..., 59) |
%S | Second, zero-padded (00, 01, ..., 59) |
%f | Microsecond, zero-padded (000000, 000001, ..., 999999) |
%z | UTC offset in the form +HHMM or -HHMM |
%Z | time zone name %j - day of the year as a zero-padded decimal number (001-366) |
%U | week number of the year (Sunday as the first day of the week) as a zero padded decimal number (00-53) |
%W | week number of the year (Monday as the first day of the week) as a decimal number (00-53) |
%c | locale's appropriate date and time representation |
%x | locale's appropriate date representation |
%X | locale'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