To convert a string to a datetime
object in Python, use the datetime
module and its strptime()
method. Here’s how to do it:
1. Basic Conversion with strptime()
Parse a string using a format code that matches the string’s structure.
from datetime import datetime
date_string = "2023-10-25 14:30:00"
# Define the format matching the string
format = "%Y-%m-%d %H:%M:%S"
# Convert string to datetime object
datetime_obj = datetime.strptime(date_string, format)
print(datetime_obj) # Output: 2023-10-25 14:30:00
2. Common Format Codes
Code | Meaning | Example |
---|---|---|
%Y | 4-digit year | 2023 |
%m | 2-digit month | 01-12 |
%d | 2-digit day | 01-31 |
%H | Hour (24h) | 00-23 |
%M | Minute | 00-59 |
%S | Second | 00-59 |
%a | Weekday (short) | Mon, Tue |
%b | Month (short) | Jan, Feb |
Example for different formats:
# Example 1: "25/10/2023"
datetime_obj = datetime.strptime("25/10/2023", "%d/%m/%Y")
# Example 2: "Oct 25, 2023 2:30 PM"
datetime_obj = datetime.strptime("Oct 25, 2023 2:30 PM", "%b %d, %Y %I:%M %p")
3. Parse ISO 8601 Strings (Python 3.7+)
Use fromisoformat()
for ISO-compliant strings:
iso_string = "2023-10-25T14:30:00"
datetime_obj = datetime.fromisoformat(iso_string)
4. Flexible Parsing with dateutil
(Third-Party)
For ambiguous formats, use dateutil.parser
(install with pip install python-dateutil
):
from dateutil import parser
date_string = "October 25, 2023 2:30 PM"
datetime_obj = parser.parse(date_string)
5. Handling Time Zones
Convert timezone-aware strings using pytz
or Python 3.9+’s zoneinfo
:
from datetime import datetime
from zoneinfo import ZoneInfo
date_string = "2023-10-25 14:30:00+05:30"
format = "%Y-%m-%d %H:%M:%S%z"
datetime_obj = datetime.strptime(date_string, format).astimezone(ZoneInfo("UTC"))
print(datetime_obj) # Output: 2023-10-25 09:00:00+00:00
Key Notes
- Format Matching: The format string must exactly match the input string.
- Error Handling: Wrap in
try-except
to catchValueError
for invalid formats:
try:
datetime_obj = datetime.strptime(date_string, format)
except ValueError:
print("Invalid format!")
- Output: The result is a
datetime
object, which you can manipulate (e.g., extract day/month/year).
Full Example
from datetime import datetime
date_str = "2023-12-31 23:59:59"
format = "%Y-%m-%d %H:%M:%S"
dt = datetime.strptime(date_str, format)
print("Year:", dt.year) # 2023
print("Month:", dt.month) # 12
print("Day:", dt.day) # 31
print("Hour:", dt.hour) # 23
print("Formatted:", dt.strftime("%A, %d %B %Y")) # Sunday, 31 December 2023
Use strptime()
for precise control, dateutil
for flexibility, and fromisoformat()
for ISO strings!