When working with raw data, dates are often provided as string objects. However, string objects do not allow direct access to attributes like the year, month, or day. To make use of these properties, you need to convert the string into a proper datetime object that Python recognizes as a date.
Python’s datetime and time modules provide a method called strptime(). This method allows you to parse date strings and transform them into datetime or struct_time objects. Once converted, you can easily extract specific date attributes or perform various date-related operations.
In this guide, you'll learn how to convert string to date in Python using strptime() method effectively. In addition, you will also explore how to convert a string to a datetime object in Python. Let’s dive in!
Format Codes For DateTime in Python
Before diving into converting strings to dates, it's essential to understand the formatting codes used by Python's datetime module. These codes act as building blocks to parse and format dates and times effectively. Below are some commonly used codes you'll encounter:
- %Y: Represents the year, ranging from 0001 to 9999.
- %m: Represents the month of the year, with values from 01 to 12.
- %d: Represents the day of the month, ranging from 01 to 31.
- %H: Represents the hour in a 24-hour clock format, ranging from 00 to 23.
- %I: Represents the hour in a 12-hour clock format, ranging from 01 to 12.
- %M: Represents the minutes of the hour, with values from 00 to 59.
- %S: Represents the seconds of the minute, with values from 00 to 59.
For a full list of format codes, you can use datetime.strptime() method, check out the "strftime() and strptime()Format Codes" section in the Python documentation.
Convert a String to a datetime Object in Python using datetime.strptime()
The datetime.strptime() method has the following syntax:
datetime.strptime(date_string, format)
This method converts a date string into a datetime object based on the specified format. Both arguments, date_string and format, are required and must be provided as strings.
Example: Converting a String to a datetime.datetime() Object
Here’s an example that demonstrates how to convert a date and time string into a datetime.datetime object. It also prints the type and value of the resulting object:
from datetime import datetime
# Example date and time string
datetime_str = '12/25/23 08:30:00'
# Convert the string to a datetime object
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')
# Print the type and value of the datetime object
print(type(datetime_object))
print(datetime_object) # Output in the default format
Output:
Example: Convert String to datetime.date() Object
Here’s an example of how to convert a date string into a datetime.date object. The code prints the type and value of the resulting object:
from datetime import datetime
# Example date string
date_str = '12-31-2023'
# Convert the string to a date object
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
# Print the type and value of the date object
print(type(date_object))
print(date_object) # Output in default format
Output:
Example: Convert String to datetime.time() Object
This example demonstrates how to convert a time string into a datetime.time object. The type and value of the resulting object are printed:
from datetime import datetime
# Example time string
time_str = '22::45::15'
# Convert the string to a time object
time_object = datetime.strptime(time_str, '%H::%M::%S').time()
# Print the type and value of the time object
print(type(time_object))
print(time_object)
Output:
Example: Convert String to datetime.datetime() Object with Locale
In this example, a French locale date string is converted into a datetime.datetime object. The type and value of the resulting object are printed:
from datetime import datetime
import locale
# Set locale to French
locale.setlocale(locale.LC_ALL, 'fr_FR')
# Example French locale date string
date_str_fr_FR = '25-Décembre-2023 Lundi' # fr_FR locale
# Convert the string to a datetime object
datetime_object = datetime.strptime(date_str_fr_FR, '%d-%B-%Y %A')
# Print the type and value of the datetime object
print(type(datetime_object))
print(datetime_object)
Note: The datetime.datetime() object doesn’t retain the weekday name (Lundi in this example) from the input string. Instead, it stores the weekday internally as a numeric value.
Converting a String to a struct_time Object Using time.strptime()
The time.strptime() method is used to parse a string into a time.struct_time object. Its syntax is as follows:
time.strptime(time_string[, format])
This method returns a time.struct_time object that corresponds to the provided time_string and format. The time_string argument is required, and both arguments must be strings. If the format is not specified, the method uses the default format:
'%a %b %d %H:%M:%S %Y'
This is the same format returned by the ctime() function. The format directives used in time.strptime() are consistent with those in time.strftime(). For more details, refer to the Python documentation on the time module.
Example: Convert String to struct_time() Object with a Custom Format
Here’s an example of converting a time string into a time.struct_time object using a custom format:
import time
# Example time string
time_str = '10::45::30'
# Convert to a struct_time object using a custom format
time_obj = time.strptime(time_str, '%H::%M::%S')
print("A time.struct_time object using the provided format:")
print(time_obj)
Output:
Note: When converting to a time.struct_time object, any unspecified format directives are filled with default placeholder values.
Example: Convert String to struct_time() Object Using the Default Format
If no format is provided, the time.strptime() method uses the default format ('%a %b %d %H:%M:%S %Y'). If the input string doesn’t match this format exactly, an error will occur.
import time
# Example time string matching the default format
time_str_default = 'Tue Mar 14 12:15:45 2023'
# Convert to a struct_time object using the default format
time_obj_default = time.strptime(time_str_default)
print("A time.struct_time object using the default format:")
print(time_obj_default)
Note: Like in the previous example, default placeholder values are used for any missing format directives when converting the string.
How to Troubleshoot strptime() Errors?
When using the strptime() method, a ValueError is raised if the input string does not match the expected format. To handle such errors gracefully, you can use a try block to test the parsing and an except block to catch and display the error messages. The ValueError messages from strptime() provide clear explanations of why the parsing failed.
Below is an example demonstrating common issues like mismatched formats or extra data:
from datetime import datetime
import time
# Example 1: Mismatched format for datetime
datetime_str = '05-25-2023 08:30:00'
try:
datetime_object = datetime.strptime(datetime_str, '%m/%d/%Y')
except ValueError as ve1:
print('Error 1:', ve1)
# Example 2: Invalid time string
time_str = '12:70:50'
try:
time_object = time.strptime(time_str, '%H:%M:%S')
except ValueError as ve2:
print('Error 2:', ve2)
Output:
Conclusion
In this tutorial, you explored how to convert strings to date and datetime objects in Python using the strptime() method. You learned how to handle various formats, parse dates, times, and even locale-specific strings. Additionally, you discovered common pitfalls, such as format mismatches, and how to troubleshoot them effectively.
Mastering string-to-date conversions is an essential skill for working with temporal data in Python. By understanding format codes and ensuring your input strings align with expected formats, you can confidently handle date and time operations in your projects.
Thank you for reading, and we hope this guide empowers you to work seamlessly with Python's robust date and time libraries!
Boost your hosting with Host-World! Enjoy reliable VPS plans starting at $7.5/month or unleash the full power of dedicated servers from $99/month—both backed by 24/7 expert support. Elevate your online presence today!