How to convert string to datetime in Python?

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

CodeMeaningExample
%Y4-digit year2023
%m2-digit month01-12
%d2-digit day01-31
%HHour (24h)00-23
%MMinute00-59
%SSecond00-59
%aWeekday (short)Mon, Tue
%bMonth (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 catch ValueError 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!

Leave a Reply

Your email address will not be published. Required fields are marked *