PythonMastery

How do I convert a string to a date in Python?

date.fromisoformat('2026-10-07') for ISO dates; datetime.strptime(text, '%d/%m/%Y') for others. The format must match the text exactly, or it's ValueError.

If the text is in ISO format (year-month-day), there's a method made for it:

python
from datetime import date, datetime

print(date.fromisoformat("2026-10-07"))
print(datetime.fromisoformat("2026-10-07 14:30"))
output
2026-10-07
2026-10-07 14:30:00

Any other format: strptime

Describe the layout of the text with the same codes strftime uses, and strptime reads it:

python
from datetime import datetime

print(datetime.strptime("07/10/2026", "%d/%m/%Y").date())
print(datetime.strptime("October 7, 2026", "%B %d, %Y").date())
print(datetime.strptime("07-Oct-2026 2:30 PM", "%d-%b-%Y %I:%M %p"))
output
2026-10-07
2026-10-07
2026-10-07 14:30:00

strptime always returns a datetime; add .date() when you only want the day. The p in the name stands for parse and the f in strftime for format, which is the easiest way to keep them apart.

When the format doesn't match

The format has to match the text exactly, separators included:

python
from datetime import datetime

try:
    datetime.strptime("2026-10-07", "%d/%m/%Y")
except ValueError as e:
    print(e)
output
time data '2026-10-07' does not match format '%d/%m/%Y'

03/04/2026: March or April?

Britain, India and most of the world read it as 3 April. The US reads it as 4 March. Python can't know which you meant; the format you pass decides:

python
from datetime import datetime

text = "03/04/2026"
print(datetime.strptime(text, "%d/%m/%Y").strftime("%d %B"))
print(datetime.strptime(text, "%m/%d/%Y").strftime("%d %B"))
output
03 April
04 March

If you control the format, as in a file you write or an API you design, use ISO (2026-04-03). Nobody misreads it, and sorting the text sorts the dates.

Many different formats in one column?

Messy data from people tends to mix them. Try each known format in turn:

python
from datetime import datetime

FORMATS = ["%Y-%m-%d", "%d/%m/%Y", "%d %B %Y"]

def parse_date(text):
    for fmt in FORMATS:
        try:
            return datetime.strptime(text.strip(), fmt).date()
        except ValueError:
            pass
    raise ValueError(f"unrecognised date: {text!r}")

for raw in ["2026-10-07", "07/10/2026", " 7 October 2026"]:
    print(parse_date(raw))
output
2026-10-07
2026-10-07
2026-10-07

In pandas, pd.to_datetime(df["date"], format="%d/%m/%Y") does a whole column in one go.

Go deeper: Dates, Times, and Timezones, Python Datetime Format Cheat Sheet

More short answers

all questions