Python .strptime()
The .strptime() method is a class method in Python’s datetime module that parses a string representing a date and time according to a specified format and returns a corresponding datetime object. It serves as the inverse operation to .strftime() by converting formatted string representations back into datetime objects that can be manipulated programmatically.
The strptime() method is essential for applications that need to process date and time data from external sources such as log files, user input, APIs, CSV files, or databases where dates are stored as strings. It enables developers to convert these string representations into Python datetime objects for calculations, comparisons, formatting, and other datetime operations. Common use cases include parsing timestamps from log files, processing user-entered dates in web forms, importing date data from spreadsheets, and converting API responses containing date strings.
Syntax
datetime.strptime(date_string, format)
Parameters:
date_string: The string containing the date and time information to be parsedformat: A string specifying the format of the input string using format directives
Return value:
Returns a datetime object representing the parsed date and time.
Example 1: Basic String Parsing
This example demonstrates the fundamental usage of .strptime() to convert a simple date string into a datetime object:
from datetime import datetime# Parse a date string in YYYY-MM-DD formatdate_string = "2024-03-15"date_object = datetime.strptime(date_string, "%Y-%m-%d")print("Original string:", date_string)print("Parsed datetime object:", date_object)print("Type:", type(date_object))# Access individual componentsprint("Year:", date_object.year)print("Month:", date_object.month)print("Day:", date_object.day)
This example results in the following output:
Original string: 2024-03-15Parsed datetime object: 2024-03-15 00:00:00Type: <class 'datetime.datetime'>Year: 2024Month: 3Day: 15
The example shows how .strptime() converts a string into a full datetime object. Notice that when only a date is provided, the time components default to 00:00:00.
Example 2: Log File Processing
This example demonstrates parsing timestamps from a log file format, which is a common real-world scenario for system administrators and developers:
from datetime import datetime# Sample log entries with timestampslog_entries = ["2024-06-09 14:30:25 INFO: User login successful","2024-06-09 14:32:18 ERROR: Database connection failed","2024-06-09 14:33:45 WARNING: High memory usage detected"]# Extract and parse timestamps from log entriesparsed_timestamps = []for entry in log_entries:# Extract timestamp part (first 19 characters)timestamp_str = entry[:19]# Parse the timestamptimestamp_obj = datetime.strptime(timestamp_str, "%Y-%m-%d %H:%M:%S")parsed_timestamps.append(timestamp_obj)print(f"Log time: {timestamp_obj}")print(f"Day of week: {timestamp_obj.strftime('%A')}")# Calculate time difference between first and last log entryif len(parsed_timestamps) > 1:time_diff = parsed_timestamps[-1] - parsed_timestamps[0]print(f"\nTime span of logs: {time_diff}")
This example results in the following output:
Log time: 2024-06-09 14:30:25Day of week: SundayLog time: 2024-06-09 14:32:18Day of week: SundayLog time: 2024-06-09 14:33:45Day of week: SundayTime span of logs: 0:03:20
This example shows practical usage for parsing server logs or application logs where timestamps need to be extracted and analyzed for monitoring, debugging, or reporting purposes.
Codebyte Example: International Date Format Processing
This example demonstrates handling various international date formats, which is crucial for applications dealing with global data sources:
This example illustrates how .strptime() can handle various date formats commonly encountered when processing data from different countries and systems.
Frequently Asked Questions
1. What’s the difference between .strptime() and .strftime()?
strptime() converts strings to datetime objects, while .strftime() converts datetime objects to formatted strings. They are inverse operations.
2. How do I handle invalid date strings using .strptime() in Python?
If the input string does not match the expected format, .strptime() will raise a ValueError. To handle such cases safely, you can use a try-except block.
3. Can .strptime() parse time-only or date-only strings in Python?
Yes, .strptime() can parse time-only or date-only strings, as long as the format string matches exactly.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours