In this lesson, you’ll learn how to convert a date string into a datetime object using datetime.strptime().
This is especially useful when working with:
The example demonstrates how to define a custom date format and parse a date string into a Python datetime object for further processing.
Let’s see how to turn raw date strings into usable time data in Python!
from datetime import datetime
date = "2022-10-15 18:41:35"
isoFormat = "%Y-%m-%d %H:%M:%S"
# new datetime parsed from a string (like time.strptime())
dt = datetime.strptime(date, isoFormat)
print(dt)
date: This variable is initialized with a string that represents a specific date and time, “2022-10-15 18:41:35”. The format used here is common and straightforward, presenting the year, month, day, hour, minute, and second.isoFormat: This variable holds the format string “%Y-%m-%d %H:%M:%S”, which is used to indicate how the components of the date string are structured. Each specifier (%Y, %m, %d, %H, %M, %S) corresponds to a part of the date string:
%Y – Four-digit year%m – Two-digit month%d – Two-digit day%H – Two-digit hour (24-hour format)%M – Two-digit minute%S – Two-digit seconddt: This datetime object is created by parsing the date string using the datetime.strptime() function, with isoFormat as the guide for parsing. The strptime() function is crucial for converting date and time formatted as strings into datetime objects based on the specified format. This allows for further manipulation or comparison with other datetime objects.datetime object dt. This display will be in the default format provided by the datetime class, which typically appears as “YYYY-MM-DD HH:MM:SS”.2022-10-15 18:41:35
from datetime import datetime
dateStr = "17 December 1989"
isoFormat = "%d %B %Y"
print(datetime.strptime(dateStr, isoFormat))
dateStr: This variable contains a string, “17 December 1989”, which represents a date. The format used here includes the day of the month, the full name of the month, and the four-digit year.isoFormat: This variable holds the format string “%d %B %Y”, which is essential for interpreting the structure of dateStr during parsing:
%d – Two-digit day of the month.%B – Full month name.%Y – Four-digit year.datetime.strptime() function to convert dateStr into a datetime object. The strptime() function is a method of the datetime class that creates a datetime object from a string representing a date and time and a corresponding format string. This function is key to converting textual date representations into datetime objects that can be manipulated within Python.datetime object, which will appear in the default format used by datetime, typically “YYYY-MM-DD HH:MM:SS”. Since no time components are provided in dateStr, the time in the output will default to 00:00:00.1989-12-17 00:00:00