Python
date conversion
datetime module
string parsing
programming tutorial

Python date string to date object

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Turning a date string into a Python date object is a standard parsing task in scripts, APIs, ETL jobs, and validation code. The normal approach is to parse the string with datetime.strptime(...) and then call .date() if you only need the calendar day rather than a full timestamp.

Parse a Known Format with strptime

If the input format is known in advance, strptime is the most direct solution. You supply the string and a format pattern that matches it exactly.

python
1from datetime import datetime
2
3text = "2024-06-15"
4date_obj = datetime.strptime(text, "%Y-%m-%d").date()
5
6print(date_obj)
7print(type(date_obj))

Output:

python
2024-06-15
<class 'datetime.date'>

strptime creates a datetime object first. The final .date() call extracts the datetime.date value, which is usually what you want when the time of day is irrelevant.

The Format String Must Match Exactly

Format codes describe how to read the string:

  • '%Y means four-digit year'
  • '%m means two-digit month'
  • '%d means two-digit day'

If the input uses a different order or different separators, the pattern must change too.

python
1from datetime import datetime
2
3text = "15/06/2024"
4date_obj = datetime.strptime(text, "%d/%m/%Y").date()
5print(date_obj)

This strict matching is where most parsing mistakes happen. If you use the wrong order, the wrong separator, or the wrong number of digits, Python raises ValueError.

Parse a Datetime String and Keep the Date

Some sources provide full timestamps even though your code only needs the date. In that case, parse the whole string and drop the time afterward.

python
1from datetime import datetime
2
3text = "2024-06-15 13:45:20"
4date_obj = datetime.strptime(text, "%Y-%m-%d %H:%M:%S").date()
5
6print(date_obj)

This is common when reading database exports, logs, or CSV files generated by other systems. You still need the full format string because strptime validates the entire input.

Use date.fromisoformat for ISO Dates

If your input is always in ISO form, YYYY-MM-DD, Python offers a shorter and very readable alternative.

python
1from datetime import date
2
3text = "2024-06-15"
4date_obj = date.fromisoformat(text)
5
6print(date_obj)

This is not a universal parser, but it is excellent when you control the data format and it is already ISO compliant.

Handle Invalid Input Cleanly

In real applications, input often comes from users or external systems. Do not assume it is always valid. Wrap parsing in try and except so bad values become validation errors instead of crashes.

python
1from datetime import datetime
2
3text = "2024-13-99"
4
5try:
6    date_obj = datetime.strptime(text, "%Y-%m-%d").date()
7    print(date_obj)
8except ValueError as exc:
9    print(f"Invalid date string: {exc}")

This is especially important in batch jobs. One malformed date should not necessarily terminate the whole run if your program can report or skip the bad row.

Support Multiple Accepted Formats

Sometimes your application must accept more than one date format. Instead of hand-splitting strings, try a small list of supported format patterns in sequence.

python
1from datetime import datetime
2
3
4def parse_date(text):
5    formats = ["%Y-%m-%d", "%d/%m/%Y", "%m-%d-%Y"]
6
7    for fmt in formats:
8        try:
9            return datetime.strptime(text, fmt).date()
10        except ValueError:
11            pass
12
13    raise ValueError(f"Unsupported date format: {text}")
14
15
16for value in ["2024-06-15", "15/06/2024", "06-15-2024"]:
17    print(parse_date(value))

This keeps the accepted formats explicit and makes the parser easier to test. It is also safer than inventing a custom parser that accidentally accepts malformed data.

date Versus datetime

The distinction between date and datetime matters. A date stores only year, month, and day. A datetime stores both date and time. If your application logic cares only about the day, returning a date object is cleaner and avoids accidental comparisons against time values later.

That is why the final .date() call is not just stylistic. It clearly signals the data type your code intends to use.

Avoid Ambiguous Input When Possible

Strings such as 01/02/2024 are ambiguous without a fixed convention. One system may read that as February 1, and another may read it as January 2. If dates move between teams, APIs, or countries, prefer ISO YYYY-MM-DD whenever possible. It reduces ambiguity and makes parsing rules easier to maintain.

If your program must support several human-facing formats, document them explicitly and keep the accepted list small.

Common Pitfalls

The most common mistake is using the wrong format string. Even a valid date fails to parse if the separators or field order do not match.

Another pitfall is forgetting that strptime returns a datetime, not a date. If your downstream code expects datetime.date, call .date().

A third issue is assuming every string is ISO formatted. Many systems use slashes, month-first ordering, or timestamps that include hours and minutes.

Finally, avoid hand-written parsing logic unless the format is truly trivial. The standard library already validates the calendar correctly, which means invalid dates such as February 30 are rejected for you.

Summary

  • Use datetime.strptime(text, format).date() when you know the input format.
  • Use date.fromisoformat(text) for simple ISO YYYY-MM-DD strings.
  • Match the format string exactly, including separators and field order.
  • Wrap parsing in try and except when the input may be invalid.
  • Return a date object instead of a datetime when your code only needs the calendar day.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.