Question

How to Parse Date Strings into datetime Objects in Python

pythondatetimetype-conversion

Question

I have a large list of date-time strings such as:

["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]

How can I convert these strings into Python datetime objects?

Short Answer

By the end of this page, you will understand how to parse formatted date strings into Python datetime objects using datetime.strptime(). You will also learn the format codes involved, how to convert an entire list, how to handle invalid values safely, and how this is commonly done in real Python code.

Concept

In Python, a date stored as a string is just text. Even if it looks like a date, Python cannot automatically treat it as a real date-time value until you parse it.

The standard way to convert a string into a datetime object is to use datetime.strptime().

strptime stands for string parse time. It reads a string according to a format pattern that you provide.

For example, this string:

Jun 1 2005 1:33PM

contains:

  • abbreviated month name: Jun
  • day of month: 1
  • year: 2005
  • hour and minute: 1:33
  • AM/PM marker: PM

So Python needs a matching format string such as:

"%b %d %Y %I:%M%p"

This matters because real programs often receive dates as strings from:

  • CSV files
  • APIs
  • logs
  • forms
  • spreadsheets
  • databases

If you want to sort dates correctly, compare them, filter by date ranges, or store them consistently, you should convert them into proper datetime objects first.

Mental Model

Think of strptime() like a date decoder.

The input string is a sentence in a specific date language:

Jun 1 2005 1:33PM

The format string is the decoder key:

"%b %d %Y %I:%M%p"

If the decoder key matches the text exactly, Python can turn the text into a real datetime object.

If the key does not match, parsing fails with an error.

So the main job is not just “convert the string,” but “describe its structure correctly.”

Take Quiz

Syntax and Examples

The basic syntax is:

from datetime import datetime

result = datetime.strptime(date_string, format_string)

For your example:

from datetime import datetime

s = "Jun 1 2005 1:33PM"
dt = datetime.strptime(s, "%b %d %Y %I:%M%p")

print(dt)

Output:

2005-06-01 13:33:00

Parsing a list of strings

from datetime import datetime

dates = ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
parsed_dates = [datetime.strptime(d, "%b %d %Y %I:%M%p") for d in dates]

print(parsed_dates)

Output:

[datetime.datetime(2005, 6, 1, 13, 33), datetime.datetime(1999, 8, 28, 0, 0)]

Format codes used here

  • %b → abbreviated month name like Jan, Feb, Jun
  • %d → day of the month as a number
  • %Y → 4-digit year
  • %I → hour in 12-hour format
  • %M → minute
  • %p → AM or PM

Why %I and not %H?

Because the string uses AM and PM, it is a 12-hour clock. That means you should use:

  • %I for the hour
  • %p for AM/PM

If the string were like 13:33, then you would use %H instead.

Step by Step Execution

Consider this example:

from datetime import datetime

text = "Aug 28 1999 12:00AM"
dt = datetime.strptime(text, "%b %d %Y %I:%M%p")
print(dt)

Here is what happens step by step:

  1. Python reads Aug and matches it to %b.

    • %b means abbreviated month name.
    • Aug becomes month 8.
  2. Python reads 28 and matches it to %d.

    • This becomes day 28.
  3. Python reads 1999 and matches it to %Y.

    • This becomes year 1999.
  4. Python reads 12 and matches it to %I.

    • %I is the 12-hour clock hour.
  5. Python reads 00 and matches it to %M.

    • This becomes minute 0.
  6. Python reads AM and matches it to %p.

    • 12:00AM is midnight, so the hour becomes 00.
  7. Python creates a datetime object:

datetime.datetime(1999, 8, 28, 0, 0)

Final printed result:

1999-08-28 00:00:00

Real World Use Cases

Parsing date strings is common in many practical situations:

  • CSV imports: reading exported reports with date columns like Jun 1 2005 1:33PM
  • API responses: converting date strings into objects before sorting or filtering
  • Log processing: turning timestamp text into datetime values for analysis
  • User input: validating and storing entered dates in a consistent format
  • Data cleaning: normalizing mixed text-based date values before saving to a database

Example: filtering records after a certain date

from datetime import datetime

rows = ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
cutoff = datetime(2000, 1, 1)

parsed = [datetime.strptime(x, "%b %d %Y %I:%M%p") for x in rows]
recent = [d for d in parsed if d >= cutoff]

print(recent)

This is much more reliable than comparing the original strings.

Take Quiz

Real Codebase Usage

In real Python projects, developers usually parse dates close to the input boundary of the system. That means the string is converted into a datetime as soon as it is read from a file, request, or external service.

Common patterns include:

Validation with error handling

from datetime import datetime


def parse_date(value):
    try:
        return datetime.strptime(value, "%b %d %Y %I:%M%p")
    except ValueError:
        return None

This is useful when some records may be invalid.

Parsing inside data pipelines

from datetime import datetime

raw_dates = ["Jun 1 2005 1:33PM", "bad value", "Aug 28 1999 12:00AM"]
parsed = []

for value in raw_dates:
    try:
        parsed.append(datetime.strptime(value, "%b %d %Y %I:%M%p"))
    except ValueError:
        pass

Guard clause style

from datetime import datetime


def parse_if_present(value):
    if not value:
        return None
    return datetime.strptime(value, "%b %d %Y %I:%M%p")

Standardizing output after parsing

Once parsed, developers often:

  • store datetime objects internally
  • convert to ISO format when sending data externally
  • compare by date ranges
  • sort records chronologically
  • extract parts like year, month, or weekday

Common Mistakes

Here are common mistakes beginners make when parsing date strings.

1. Using the wrong hour code

Broken code:

from datetime import datetime

datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %H:%M%p")

Problem:

  • %H is for a 24-hour clock
  • %p is for AM/PM
  • these usually should not be combined for this input

Use this instead:

datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M%p")

2. Forgetting %p

Broken code:

datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M")

Problem:

  • the string still contains PM
  • the format does not account for it

3. Using %m instead of %b

Broken code:

datetime.strptime("Jun 1 2005 1:33PM", "%m %d %Y %I:%M%p")

Problem:

  • %m expects a numeric month like 06
  • your string uses a month name like Jun

4. Assuming strings are dates already

Broken idea:

items = ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
items.sort()

Problem:

  • this sorts alphabetically, not by actual chronological meaning

Better:

from datetime import datetime

items = ["Jun 1 2005 1:33PM", "Aug 28 1999 12:00AM"]
items = [datetime.strptime(x, "%b %d %Y %I:%M%p") for x in items]
items.sort()

5. Not handling invalid input

If one string has a different format, strptime() raises ValueError.

Use try/except if your data may be messy.

Comparisons

TaskBest ChoiceWhy
Convert a date string into a datetimedatetime.strptime()Designed for parsing known formats
Convert a datetime into a stringdatetime.strftime()Designed for formatting output
Parse 1:33PM style hours%I with %p12-hour clock with AM/PM
Parse 13:33 style hours%H24-hour clock
Parse abbreviated month like Jun%bMatches short month names
Parse numeric month like 06%mMatches numbers, not names

strptime() vs strftime()

FunctionDirectionExample
strptime()string → datetimedatetime.strptime("Jun 1 2005 1:33PM", fmt)
strftime()datetime → stringdt.strftime("%Y-%m-%d %H:%M")

List comprehension vs loop

ApproachWhen to use it
List comprehensionWhen all values are expected to be valid
for loop with try/exceptWhen some values may be invalid and need handling
Take Quiz

Cheat Sheet

from datetime import datetime

Parse one string

dt = datetime.strptime("Jun 1 2005 1:33PM", "%b %d %Y %I:%M%p")

Parse a list

parsed = [datetime.strptime(x, "%b %d %Y %I:%M%p") for x in values]

Format string for this question

"%b %d %Y %I:%M%p"

Important format codes

  • %b = abbreviated month name (Jan, Jun, Aug)
  • %d = day of month
  • %Y = 4-digit year
  • %I = hour, 12-hour clock
  • %M = minute
  • %p = AM or PM

Rules

  • Use %I when the time includes AM or PM
  • Use %H for 24-hour time like 13:33
  • The format string must match the input structure exactly
  • Invalid input raises ValueError

Safe parsing pattern

def parse_date(value):
    try:
        return datetime.strptime(value, "%b %d %Y %I:%M%p")
    except ValueError:
        return None

FAQ

How do I convert a string to a datetime object in Python?

Use datetime.strptime(string, format) and provide a format string that matches the text exactly.

What format string matches Jun 1 2005 1:33PM?

Use:

"%b %d %Y %I:%M%p"

Why do I need %I instead of %H?

Because the input uses AM or PM, which means it uses a 12-hour clock.

Can I parse a whole list of date strings at once?

Yes. A list comprehension is common:

parsed = [datetime.strptime(x, "%b %d %Y %I:%M%p") for x in values]

What happens if one string is invalid?

datetime.strptime() raises ValueError. Use try/except if the input may contain bad data.

Does 12:00AM mean noon or midnight?

12:00AM means midnight. 12:00PM means noon.

Can I sort the original strings instead of converting them?

You should usually parse them first. Sorting text does not always produce correct chronological order.

Take Quiz

Mini Project

Description

Build a small parser for imported date strings. Imagine you receive timestamp values from a CSV export and need to convert them into real Python datetime objects before sorting and validating them.

Goal

Create a function that converts a list of date strings into datetime objects and safely skips invalid entries.

Requirements

  1. Accept a list of strings in the format Jun 1 2005 1:33PM.
  2. Convert each valid string into a Python datetime object.
  3. Ignore invalid values without crashing.
  4. Return the successfully parsed dates in chronological order.
Take Quiz

Keep learning

Related questions

View more