Explain Codes LogoExplain Codes Logo

Python date string to date object

python
dateutil
datetime
date-string
Alex KataevbyAlex Kataev·Mar 3, 2025
⚡TLDR

In Python, you can convert date strings to datetime.date objects quickly using datetime.strptime with the proper string format. Don't forget to call .date() to ensure it's a day, not a moment:

from datetime import datetime # Hey Python, "23-04-2023" is a date. Trust me! date_object = datetime.strptime("2023-04-12", "%Y-%m-%d").date()

Managing different date formats

Date strings come in various patterns. Use format codes in strptime to define the structured hint:

  • "%Y-%m-%d" for "2023-04-12"
  • "%d/%m/%Y" for "12/04/2023"
  • "%m/%d/%Y" for "04/12/2023"
  • "%B %d, %Y" for "April 12, 2023"
from datetime import datetime # ISO, Euro, US dates # Just like basketball teams, but with less sweat date_object_iso = datetime.strptime("2023-04-12", "%Y-%m-%d").date() date_object_euro = datetime.strptime("12/04/2023", "%d/%m/%Y").date() date_object_us = datetime.strptime("04/12/2023", "%m/%d/%Y").date() # Show-off date, for formal invitations and PhD theses. date_object_full = datetime.strptime("April 12, 2023", "%B %d, %Y").date()

Pitfalls to avoid:

  • Forgetting .date() can return unwanted 00:00:00 time.
  • Format inconsistency can throw a party-ruining ValueError.

Handling irregular date formats

For handling diverse and bizarre date strings, take advantage of dateutil.parser.parse:

from dateutil import parser # Flexible, like a gymnast complex_date_string = "Wed, 12 April 2023" date_object_flexible = parser.parse(complex_date_string).date()

While dateutil.parser.parse can handle the flex, remember it defaults to a datetime object – add .date() to maintain calendar sanity!

During parsing, a bevy of errors may appear:

  • ValueError: Check your strptime format.
  • Locale errors: Keep an eye on locale settings for month and day names.
  • Timezone blues: Handle tzinfo when using dateutil.parser.parse.

Ensuring conversion accuracy

Try out these assertions to ensure your date object is spot on:

# Auditing the result - 'cause even Python can make mistakes! assert date_object.year == 2023 assert date_object.month == 3 assert date_object.day == 14

Reversing the process: Date object to string

Need to reverse-engineer the object back into a string? Use strftime!

# The spy who came in from the cold(date object) formatted_date_string = date_object.strftime("%Y-%m-%d")

Alter the format string to tailor it to your styling desires.