← Back to Articles
Tutorial

Understanding Python strptime Function

Learn how to use Python's strptime for parsing dates and times.

Python's strptime function is a powerful tool for parsing strings into datetime objects. It is part of the datetime module, which provides various functions to handle dates and times in Python. The strptime function allows you to convert a date string into a datetime object according to a specified format, facilitating further manipulation and analysis.

The strptime function takes two main arguments: the date string you want to parse and the format string that specifies how the date string is structured. For example, if you have a date string in the format '2023-10-15', you would use '%Y-%m-%d' as the format string. This tells Python how to interpret the string and convert it into a datetime object. Here's an example: `datetime.strptime('2023-10-15', '%Y-%m-%d')`.

To effectively use strptime, it's important to be familiar with the format codes that represent different components of a date and time. Common codes include '%Y' for the full year, '%m' for the month, and '%d' for the day. Additionally, ensure that your date strings match the expected format to avoid parsing errors.

One common mistake is mismatching the date string and format string, which can lead to errors. Always double-check the format codes and ensure the string follows the expected pattern. Additionally, be cautious with locale-specific formats, as strptime may behave differently across locales.

Code Examples

Example 1

from datetime import datetime

# Parse a date string
parsed_date = datetime.strptime('2023-10-15', '%Y-%m-%d')
print(parsed_date)

Example 2

from datetime import datetime

# Parse a date and time string
parsed_datetime = datetime.strptime('15/10/2023 14:30', '%d/%m/%Y %H:%M')
print(parsed_datetime)

More Python Tutorials