How to Convert String to Date/Time in Python Using strptime()

The strptime() method, short for “string parse time”, is a part of Python’s datetime module. It converts a string representation of a date and time into a datetime object.

This method is particularly useful when you need to read dates and times from various formats and convert them into a unified format for processing or storage.

If you need to go the other way—converting datetime objects back into formatted strings—use the strftime() method (it uses the same format codes).

Let’s explore the strptime() method in detail, including its syntax, format codes, and practical examples.

Syntax

The syntax of the strptime() method is as follows:

datetime.strptime(date_string,format_string)

Where,

date_string: A string containing the date and time you want to convert.

format_string: A format string that specifies how the date and time are arranged within your date_string.

Basic Examples

To construct a datetime object from a string using the strptime() method, you need to tell Python how to extract pieces of date and time information from your input string. This is achieved through the use of formatting codes.

For example, if you have a date string like “2024-03-01” and you want to convert this into a datetime object, you would use the strptime() method along with the appropriate formatting codes to indicate the order and format of the year, month, and day in the string. In this case, the format string would be %Y-%m-%d, where %Y represents a year, %m represents a month, and %d represents a day of the month.

Let’s illustrate this with an example:

from datetime import datetime

# Sample date string
date_string = "2024-03-01"

# Convert the string to datetime object
datetime_object = datetime.strptime(date_string, "%Y-%m-%d")

print(datetime_object)
# Output: 2024-03-01 00:00:00

Format codes in strptime() always begin with a percentage sign %, which follows an old C standard. These codes resemble the old printf string formatting style, but they are not the same.

Handling Errors

Note that if the provided string does not match the format string, strptime() will raise a ValueError. To manage these potential errors effectively, it is good practice to implement exception handling using try-except blocks.

from datetime import datetime

# Invalid date string
date_string = "2024-15-01"

try:
    datetime_object = datetime.strptime(date_string, "%Y-%m-%d")
except ValueError as e:
    print("Error:", e)

# Output: Error: time data '2024-15-01' does not match format '%Y-%m-%d'

List of Format Codes

The format string can include various format codes. Each code acts as a placeholder that tells the strptime() method how to extract pieces of date and time information from your input string.

Below are tables of all format codes with explanations and examples. Note that the examples are based on the specific datetime of 2024-03-01 19:33:27 for demonstration purposes.

Format codes for Date

CodeExample Input
(2024-03-01 19:33:27)
Meaning
%aFriAbbreviated weekday name
%AFridayFull weekday name
%w5Weekday as a decimal number (0=Sunday, 6=Saturday)
%d01Day of the month as a zero-padded decimal number
%bMarAbbreviated month name
%BMarchFull month name
%m03Month as a zero-padded decimal number
%y24Year without century as a zero-padded decimal number
%Y2024Year with century as a decimal number

Format codes for Time

CodeExample Input
(2024-03-01 19:33:27)
Meaning
%H19Hour in 24-hour format (00-23)
%I07Hour in 12-hour format (01-12)
%pPMAM/PM
%M33Minute as a zero-padded decimal number
%S27Second as a zero-padded decimal number
%f148285Microsecond as a decimal number (000000-999999)
%z-0500 (if EST is your timezone)UTC offset in the form +/-HHMM[SS[.ffffff]]
%ZEST (if EST is your timezone)Time zone name

Format codes for Alternative Representations

CodeExample Input
(2024-03-01 19:33:27)
Meaning
%j061Day of the year as a zero-padded decimal number (001-366)
%U08Week number of the year (Sunday is first day of the week) 00-53
%W09Week number of the year (Monday is first day of the week) 00-53
%cFri Mar 1 19:33:27 2024Locale’s date and time representation
%x03/01/24Locale’s date representation
%X19:33:27Locale’s time representation

Converting a Simple Date Format

Let’s look at a few more examples that convert date strings in different formats— one in the American format (month/day/year) and the other in the European format (day-month-year)—into datetime objects.

from datetime import datetime

# American date format
datetime_object = datetime.strptime("12/25/2024", "%m/%d/%Y")
print(datetime_object)
# Output: 2024-12-25 00:00:00

# European date format
datetime_object = datetime.strptime("15-03-2024", "%d-%m-%Y")
print(datetime_object)
# Output: 2024-03-15 00:00:00

Note that since no time is provided, the time defaults to midnight (00:00:00).

Converting a Full Date-Time String

Let’s parse a string that includes both date and time. %H, %M, and %S are used to match hours, minutes, and seconds, respectively. This format assumes a 24-hour clock.

from datetime import datetime

# Date and time format
datetime_string = "2024-03-01 15:30:45"
datetime_object = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")

print(datetime_object)
# Output: 2024-03-01 15:30:45

Converting 12-Hour Time Formats with AM/PM

This example demonstrates how to parse dates that use a 12-hour time format with AM/PM. In this case, %I is used to represent the hour in a 12-hour format, while %p is used to distinguish between AM and PM.

from datetime import datetime

# Date with 12-hour time format with AM/PM
datetime_string = "03/01/2023 09:45 PM"
datetime_object = datetime.strptime(datetime_string, "%m/%d/%Y %I:%M %p")

print(datetime_object)
# Output: 2023-03-01 21:45:00

Converting ISO 8601 Format

Different cultures around the world have their own conventions for formatting dates. For example, the United States typically uses the month-day-year format (02-29-2024), while many European countries use the day-month-year format (29-02-2024). These variations can lead to miscommunication, especially in international contexts.

To address this, the International Organization for Standardization (ISO) created the ISO 8601 standard. This standard establishes a clear and unambiguous date and time format, with components arranged from most significant to least:

YYYY-MM-DDTHH:MM:SS.mmmmmm

The example below shows how to parse a date-time string in ISO 8601 format:

from datetime import datetime

# ISO 8601 format string
datetime_string = "2024-03-01T14:30:00"

# Parse the string into a datetime object
datetime_object = datetime.strptime(datetime_string, "%Y-%m-%dT%H:%M:%S")

print(datetime_object)
# Output: 2024-03-01 14:30:00

Converting Day of the Year and Week Number

This example shows how to parse a date string representing the year, the week number of the year, and the day of the week into a datetime object. In this case, the year is represented by %Y, the week number by %U, and the weekday by %w.

from datetime import datetime

# Day of the year and week number
datetime_string = "2024 33 6"
datetime_object = datetime.strptime(datetime_string, "%Y %U %w")

print(datetime_object)
# Output: 2024-08-24 00:00:00

Converting Locale-specific Date Formats

Locale-specific date formats present date and time information in a way that is understandable and familiar to users in a particular locale. For example, the month “January” in the US locale becomes “Janvier” in the French locale.

This example demonstrates parsing a locale-specific date format, in this case, French. %B is used for the full month name. When parsing locale-specific dates, always ensure your environment’s locale settings match the date string’s language, or use a module like locale to handle locale settings in Python.

from datetime import datetime
import locale

# Set French locale
locale.setlocale(locale.LC_TIME, 'fr_FR')

# Locale-specific date format
datetime_string = "15 Janvier 2024"
datetime_object = datetime.strptime(datetime_string, "%d %B %Y")

print(datetime_object)
# Output: 2024-01-15 00:00:00

Converting Date-Time with Time zone Information

This example shows parsing a date and time string that includes time zone information. The %z code is used to parse the UTC offset.

from datetime import datetime

# Date and time with UTC offset
datetime_string = "2024-03-01 15:30:45+0400"
datetime_object = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S%z")

print(datetime_object)
# Output: 2024-03-01 15:30:45+04:00

print(datetime_object.tzinfo)
# Output: UTC+04:00

Notice that the resulting datetime object is timezone-aware, meaning it includes information about its time zone. This is crucial in applications that handle dates and times across different regions, ensuring you are making correct time-related calculations.

Converting Strings to TimeStamps

Unix timestamps (also known as POSIX time or epoch time) are often used to store and compare points in time in a way that’s independent of time zones.

If you have a string representing a date and time, you can first use strptime() to convert this string into a datetime object, and then use the timestamp() method to convert this datetime object into a timestamp.

Here’s how you can convert a string into a Unix timestamp:

from datetime import datetime

# Convert string to datetime object
datetime_string = "2024-03-01 15:30:45"
datetime_object = datetime.strptime(datetime_string, "%Y-%m-%d %H:%M:%S")

# Convert datetime object to timestamp
timestamp = datetime_object.timestamp()

print("Datetime Object:", datetime_object)  # Datetime Object: 2024-03-01 15:30:45
print("Timestamp:", timestamp)              # Timestamp: 1709287245.0