0
0
PythonHow-ToBeginner · 3 min read

How to Parse Date String in Python Easily

To parse a date string in Python, use the datetime.strptime() method from the datetime module. This method converts a date string into a datetime object by specifying the string format.
📐

Syntax

The basic syntax to parse a date string is:

  • datetime.strptime(date_string, format)

Here:

  • date_string is the string containing the date you want to convert.
  • format is a string that tells Python how the date is structured, using special codes like %Y for year, %m for month, and %d for day.
python
from datetime import datetime

parsed_date = datetime.strptime('2024-06-15', '%Y-%m-%d')
💻

Example

This example shows how to convert a date string like '15/06/2024' into a Python datetime object using the correct format.

python
from datetime import datetime

# Date string to parse
date_string = '15/06/2024'

# Parse using the format day/month/year
parsed_date = datetime.strptime(date_string, '%d/%m/%Y')

print('Parsed date:', parsed_date)
print('Year:', parsed_date.year)
print('Month:', parsed_date.month)
print('Day:', parsed_date.day)
Output
Parsed date: 2024-06-15 00:00:00 Year: 2024 Month: 6 Day: 15
⚠️

Common Pitfalls

Common mistakes when parsing date strings include:

  • Using the wrong format codes that don't match the date string.
  • Mixing up day and month positions.
  • Not handling time parts if present.

For example, parsing '06/15/2024' with format '%d/%m/%Y' will cause an error because the day and month are swapped.

python
from datetime import datetime

# Wrong format example
try:
    wrong_date = datetime.strptime('06/15/2024', '%d/%m/%Y')
except ValueError as e:
    print('Error:', e)

# Correct format example
correct_date = datetime.strptime('06/15/2024', '%m/%d/%Y')
print('Correctly parsed:', correct_date)
Output
Error: time data '06/15/2024' does not match format '%d/%m/%Y' Correctly parsed: 2024-06-15 00:00:00
📊

Quick Reference

Here are some common format codes used in strptime:

Format CodeMeaningExample
%Y4-digit year2024
%y2-digit year24
%m2-digit month06
%d2-digit day15
%HHour (24-hour)14
%IHour (12-hour)02
%MMinute30
%SSecond59
%pAM or PMPM

Key Takeaways

Use datetime.strptime() with the correct format string to parse date strings.
Match the format codes exactly to the date string structure to avoid errors.
Common format codes include %Y for year, %m for month, and %d for day.
Parsing errors often happen due to swapped day and month positions.
You can extract year, month, and day from the parsed datetime object easily.