Convert a Python String to a Datetime Object

When a timestamp string always follows the same structure, convert it into a datetime object with datetime.strptime(). For ISO-formatted strings coming from APIs or logs, use datetime.fromisoformat().

from datetime import datetime

dt = datetime.strptime("2024-06-15 10:30:00", "%Y-%m-%d %H:%M:%S")
print(dt)  # 2024-06-15 10:30:00

strptime() returns a datetime.datetime object that you can compare, subtract, or provide to strftime(). If the input format is inconsistent, install python-dateutil and use dateutil.parser.parse().

This guide covers all three parsing approaches, important format directives, time zones, error handling, and time.strptime() for older workflows that require struct_time output.

Deploy Python applications from GitHub with a managed application platform and allow the hosting platform to handle application scaling.

Python String to Datetime: Key Takeaways

  • datetime.strptime(string, format) requires a predefined layout, and both parameters are strings.
  • datetime.fromisoformat(string) is suitable for ISO 8601 values such as 2024-06-15T10:30:00+05:30 with Python 3.11 and newer.
  • dateutil.parser.parse(string) determines the format automatically. It is useful for user-provided values but is not ideal for CSV files containing millions of rows.
  • strftime() converts a datetime into a string. A useful reminder is that parse corresponds to strptime, while format corresponds to strftime.
  • .date() and .time() remove the datetime components you do not require.
  • An incorrect format raises ValueError. Handle parsing with try/except or test several format strings in a loop.
  • %z parses offsets such as +0530. On Python 3.11 and newer, fromisoformat() also accepts an offset such as +05:30 that includes a colon.
  • time.strptime() produces struct_time. For most applications, datetime.strptime() is the better choice.
  • Python 3.12 and 3.13 on Ubuntu 24.04 LTS use these APIs in the same way. Begin with the standard library before introducing additional packages.

Prerequisites for Parsing Datetime Strings in Python

  • Python 3.8 or newer. Python 3.11+ provides the broadest fromisoformat() support.
  • You are familiar with strings and the datetime module.
  • Optional: python-dateutil. Install it with pip:

pip install python-dateutil

Choose a Python Datetime Parsing Method

Method Format String Required Dependency Timezone-Aware Best Use
datetime.strptime() Yes stdlib With %z Logs, CSV files, and fixed formats
datetime.fromisoformat() No stdlib Yes (3.11+) ISO timestamps from JSON and APIs
dateutil.parser.parse() No python-dateutil Often Mixed formats and human-readable dates
time.strptime() Yes stdlib Limited Older C-style struct_time workflows

Common Python strptime() Format Directives

Directive Meaning Example Input Parsed Value
%Y Four-digit year 2024 2024
%y Two-digit year 24 2024
%m Month (01-12) 06 June
%d Day (01-31) 15 15th
%H 24-hour clock hour (00-23) 14 2 p.m.
%I 12-hour clock hour (01-12) 02 2 when combined with %p
%M Minute 30 30
%S Second 00 0
%f Microsecond 123456 123456 µs
%p AM/PM PM Afternoon
%z UTC offset +0530 +5:30
%Z Time zone name UTC Name, depending on the platform
%A / %a Full or abbreviated weekday Friday / Fri Weekday
%B / %b Full or abbreviated month June / Jun Month

The complete set is available in the strftime() and strptime() format codes documentation.

Method 1: Parse Python Strings with datetime.strptime()

datetime.strptime(date_string, format) compares the supplied format directives with the input string and produces a datetime object.

Parse a Date and Time String

from datetime import datetime

datetime_str = '09/19/22 13:55:26'
datetime_object = datetime.strptime(datetime_str, '%m/%d/%y %H:%M:%S')

print(type(datetime_object))
print(datetime_object)

Output:

<class 'datetime.datetime'>
2022-09-19 13:55:26

Parse Only a date or time

from datetime import datetime

date_str = '09-19-2022'
date_object = datetime.strptime(date_str, '%m-%d-%Y').date()
print(date_object)  # 2022-09-19

time_str = '13:55:26'
time_object = datetime.strptime(time_str, '%H:%M:%S').time()
print(time_object)  # 13:55:26

Parse mm dd yyyy and ISO-Style Strings

from datetime import datetime

print(datetime.strptime("12 25 2024", "%m %d %Y"))
print(datetime.strptime("2024-12-25", "%Y-%m-%d"))

# Three-digit milliseconds use %f (microseconds). Python pads with zeros.
print(datetime.strptime("2024-06-15 10:30:00.123", "%Y-%m-%d %H:%M:%S.%f"))

Output:

2024-12-25 00:00:00
2024-12-25 00:00:00
2024-06-15 10:30:00.123000

Method 2: Parse ISO Strings with fromisoformat()

datetime.fromisoformat() can interpret many ISO 8601 strings without requiring you to define a format manually. This type of timestamp commonly appears in REST APIs and databases.

from datetime import datetime

print(datetime.fromisoformat("2024-06-15T10:30:00"))
print(datetime.fromisoformat("2024-06-15T10:30:00+05:30"))

Output:

2024-06-15 10:30:00
2024-06-15 10:30:00+05:30

Python version information:

  • 3.7+: Supports YYYY-MM-DD and basic T separators.
  • 3.11+: Supports additional ISO variations, including several timezone formats.
  • 3.6-3.10: Supports a more limited range. For unusual strings, consider dateutil.parser.parse().

A string that ends with Z represents UTC. With older Python versions, replace Z with +00:00 before parsing:

s = "2024-06-15T10:30:00Z"
dt = datetime.fromisoformat(s.replace("Z", "+00:00"))

Method 3: Flexible Datetime Parsing with dateutil

If individual rows use different layouts, dateutil.parser.parse() can determine the format automatically:

from dateutil import parser

print(parser.parse("Jun 1 2005 1:33PM"))
print(parser.parse("2024-06-15"))

First run pip install python-dateutil.

parse() requires more CPU when processing very large files because the package examines every input string. When all rows use the same structure, prefer strptime().

Parse Human-Readable Dates with a Fixed Format

You do not need dateutil to parse Jun 1 2005 1:33PM. You can define its structure explicitly:

from datetime import datetime

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

Output:

There is no space before %p because the source string places PM immediately after the minutes.

Parse Python Datetime Strings with Timezone Offsets

For a numeric offset, use strptime() with %z. In this example, the offset does not contain a colon:

from datetime import datetime

dt = datetime.strptime("2024-06-15 10:30:00+0530", "%Y-%m-%d %H:%M:%S%z")
print(dt)  # timezone-aware

On Python 3.11 and newer, an ISO offset containing a colon can be parsed with fromisoformat():

from datetime import datetime

dt = datetime.fromisoformat("2024-06-15T10:30:00+05:30")

Named time zones such as America/New_York require zoneinfo, which is included in the standard library starting with Python 3.9. Parse the local time without timezone information first and then assign the zone.

Handle ValueError and Multiple Datetime Formats

Additional text or an incorrect format causes Python to raise ValueError:

from datetime import datetime

datetime_str = '09/19/18 13:55:26'

try:
    datetime.strptime(datetime_str, '%m/%d/%y')
except ValueError as err:
    print(err)  # unconverted data remains:  13:55:26

When several layouts are possible, test each format until one succeeds:

from datetime import datetime

def parse_flexible(value: str):
    formats = ("%Y-%m-%d", "%m/%d/%Y", "%d-%m-%Y")
    for fmt in formats:
        try:
            return datetime.strptime(value, fmt)
        except ValueError:
            continue
    raise ValueError(f"no format matched: {value!r}")

print(parse_flexible("2024-06-15"))

When parsing a row fails, record the original string in your logs. This makes incorrect data easier to identify and correct.

Convert a Python datetime Back to a String with strftime()

strftime() performs the opposite operation of strptime(): it converts an object into a string.

from datetime import datetime

date_object = datetime.strptime("12 25 2024", "%m %d %Y")
print(date_object.strftime("%Y-%m-%d"))      # 2024-12-25
print(date_object.strftime("%d, %m, %Y"))    # 25, 12, 2024

This approach is useful for yyyy-mm-dd filenames, SQL literals, and JSON fields.

Parse Strings with time.strptime() and struct_time

The time module provides time.strptime(). Its result is a time.struct_time tuple rather than a datetime object:

import time

time_str = 'Mon Dec 12 14:55:02 2022'
time_obj = time.strptime(time_str)  # default format
print(time_obj.tm_year, time_obj.tm_mon, time_obj.tm_mday)

If you omit the format parameter, Python expects '%a %b %d %H:%M:%S %Y'.

If you need a datetime, create one from the tuple:

from datetime import datetime
import time

struct = time.strptime("Mon Dec 12 14:55:02 2022")
print(datetime(*struct[:6]))

For new projects, use datetime.strptime() as the default approach.

Parse Date Columns with Pandas

pandas.to_datetime() can convert an entire column at once. Provide format in the same way you would with strptime, or use format=None to let Pandas determine the format:

import pandas as pd

df = pd.DataFrame({"logged_at": ["2024-06-15", "2024-06-16"]})
df["logged_at"] = pd.to_datetime(df["logged_at"], format="%Y-%m-%d")
print(df.dtypes)

If a single column contains mixed formats, set errors="coerce". Invalid rows then become NaT rather than terminating the operation. If DataFrames are unfamiliar, begin with a Pandas module tutorial.

Parse Locale-Specific Month Names

Month names in languages other than English require a locale that is available on the operating system:

from datetime import datetime
import locale

locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
dt = datetime.strptime('16-Dezember-2022', '%d-%B-%Y')
print(dt)

If setlocale does not work, install the required language pack or keep month names in English and parse them with %B or %b.

Frequently Asked Questions About Python String to Datetime Conversion

1. How Can You Convert a String to a Datetime in Python?

Call datetime.strptime() and provide a format string:

from datetime import datetime

dt = datetime.strptime("2024-12-25", "%Y-%m-%d")

For ISO timestamps, use datetime.fromisoformat("2024-12-25T10:30:00").

2. What Does strptime() Do?

strptime() refers to string parse time. You define the expected structure using format directives such as %Y, %m, %d, and others. The datetime version returns a datetime object, while the version in the time module returns struct_time. Neither one automatically determines the input format.

3. What Is strftime() in Python?

strftime() turns a datetime object into a string. It uses the same format codes as strptime(), but the conversion runs in the opposite direction. For example, dt.strftime("%Y-%m-%d") outputs 2024-06-15.

4. How Do You Use strptime() and strftime() Together?

First parse the value, then modify the object when necessary, and finally format it:

from datetime import datetime

raw = "12/25/2024"
dt = datetime.strptime(raw, "%m/%d/%Y")
iso = dt.strftime("%Y-%m-%d")
print(iso)  # 2024-12-25

5. How Can You Convert a String to a Timestamp in Python?

Parse the string first and then call .timestamp() to obtain Unix seconds:

from datetime import datetime

dt = datetime.strptime("2024-06-15 10:30:00", "%Y-%m-%d %H:%M:%S")
print(int(dt.timestamp()))

Timezone-aware datetime objects follow UTC rules. When working with struct_time, pass the tuple produced by time.strptime() to time.mktime(), which uses local-clock semantics.

6. How Do You Get a date Instead of a datetime?

Parse the string and then call .date():

from datetime import datetime

d = datetime.strptime("12 25 2024", "%m %d %Y").date()
print(d)  # 2024-12-25

7. Is dateutil.parser.parse() Slower Than strptime()?

Yes, particularly for large files with a consistent format. dateutil analyzes every individual string. CSV files and log columns with a fixed structure are processed more efficiently with strptime() or pandas.to_datetime().

What to Do Next

You now have three main options: use strptime() when the format is fixed, choose fromisoformat() for ISO fields from APIs, and use dateutil.parser when input strings vary. Add timezone handling before using the code in production, protect untrusted input with try/except, and use strftime() whenever you need to export the resulting values as strings again.

Source: digitalocean.com

Create a Free Account

Register now and get access to our Cloud Services.

Posts you might be interested in: