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_stringis the string containing the date you want to convert.formatis a string that tells Python how the date is structured, using special codes like%Yfor year,%mfor month, and%dfor 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 Code | Meaning | Example |
|---|---|---|
| %Y | 4-digit year | 2024 |
| %y | 2-digit year | 24 |
| %m | 2-digit month | 06 |
| %d | 2-digit day | 15 |
| %H | Hour (24-hour) | 14 |
| %I | Hour (12-hour) | 02 |
| %M | Minute | 30 |
| %S | Second | 59 |
| %p | AM or PM | PM |
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.