Member-only story
When processing data, especially log files or user inputs, we often encounter dates and times stored as plain text within strings. To work with such data programmatically, we must convert string representations of dates and times into actual date and time objects. Thankfully, Python comes equipped with robust libraries capable of parsing even complex date and time formats.
This comprehensive guide demonstrates how to utilize these tools effectively.
Using datetime.strptime()
The core function responsible for converting strings to date/time objects resides in the datetime
module called strptime
. We supply a custom format string along with our input string, allowing us to control precisely how Python interprets incoming information.
Let’s examine a few examples illustrating different scenarios:
from datetime import datetime
input_string1 = '2023-03-08'
format_string1 = '%Y-%m-%d'
parsed_date1 = datetime.strptime(input_string1, format_string1)
print(f"Parsed date: {parsed_date1} ({type(parsed_date1)})")
input_string2 = 'Mar 8th, 2023'
format_string2 = '%b…