Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk4 min

Convert a String to datetime in Python (strptime and ISO)

Use strptime() for known custom patterns and fromisoformat() for ISO 8601. Learn the format codes, version differences, and the traps that silently give wrong dates.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use datetime.strptime(text, format) when the string follows a known custom pattern, and datetime.fromisoformat(text) when it is an ISO 8601 timestamp. Both return a datetime object, and both raise ValueError if the input is malformed or doesn’t match. This guide covers when to pick each, the format codes you’ll actually need, and the traps (missing years, timezones, ambiguous strings) that produce wrong dates without any error. Details follow the Python 3.14 datetime documentation.

The two calls side by side

Custom format:

from datetime import datetime

value = datetime.strptime("2026-10-05 14:30", "%Y-%m-%d %H:%M")

ISO timestamp with an offset:

from datetime import datetime

value = datetime.fromisoformat("2026-10-05T14:30:00+00:00")

The first returns a naive datetime (no timezone); the second returns a timezone-aware one because the string carries an offset.

Choosing the parser

Question Use strptime() Use fromisoformat()
Input shape Any known custom pattern, e.g. 05/10/2026 2:30 PM ISO 8601 forms Python supports
Needs a format string Yes No
Python version sensitivity Low High: before 3.11 it accepted only output of isoformat(); 3.11 broadened it
Timezone Only if you include %z Aware if the string has Z or a numeric offset

When to use strptime()

Each directive in the format string describes one component of the input, and the format must match the input’s field order and separators. If it can’t, you get a ValueError.

When to use fromisoformat()

The 3.14 docs show it handling date-only strings, compact dates, week dates, a T or space separator, a trailing Z, and numeric UTC offsets. Because acceptance widened in Python 3.11, code that relies on newer forms such as a trailing Z should state a minimum Python version.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“ISO” does not mean every ISO 8601 form

The documented exceptions are reduced-precision dates (YYYY-MM and YYYY), extended signed-year forms, ordinal dates (YYYY-OOO), and fractional hours or minutes. For those, use strptime() with an explicit format or handle the string yourself.

Date-only or time-only data

If there is no time component, parse to a date; if there is no date, parse to a time. The standard library has separate parsing methods for date, datetime and time, so you don’t invent a midnight that wasn’t in the data.

Format codes you’ll use most

Code Meaning
%Y Year with century (normally four digits)
%y Year without century
%m Month number
%d Day of month
%H:%M:%S 24-hour time
%I:%M %p 12-hour time with AM/PM; %p affects the hour only when %I is used
%f Fractional seconds as microseconds; strptime() accepts one to six digits and zero-pads on the right
%z UTC offset; in strptime() a colon may separate offset parts, and Z is equivalent to +00:00

strptime() parses a string into an object; strftime() goes the other way and formats an object as a string. They are not interchangeable.

ISO week dates

%G is the ISO week-year, %V the ISO week number, and %u the ISO weekday. The ISO week-year doesn’t always equal the calendar year, so don’t swap %G for %Y. Incomplete or ambiguous combinations of these directives can raise ValueError.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Pitfalls that produce wrong or failing results

1. Omitted fields take defaults

For datetime.strptime() and date.strptime(), anything you leave out comes from 1900-01-01T00:00:00.000. A format with no year therefore silently uses 1900.

2. February 29 without a year

1900 is not a leap year, so “02-29” fails to parse. Include a year. If you must parse partial month/day values that could be February 29, append a known leap year for parsing, then handle the result according to what your application means by that date. The 3.14 docs add that a day-of-month format without a year raises a DeprecationWarning, and such values may error as of Python 3.15.

3. Compact strings with no separators

The docs give %Y%m%d against 2026111 as an example that could be read as November 1 or January 11. Use separators, or fixed-width zero-padded input, so there’s only one reading.

4. Timezone meaning

A numeric offset or Z yields an aware datetime; a string without one yields a naive datetime, which doesn’t identify an absolute moment. Keep or assign timezone meaning deliberately based on what your data source promises. Don’t silently treat local time as UTC.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

5. Platform and locale variation

Python relies on the platform C library, so the set of supported format codes can differ between systems, and locale-dependent month and day names can vary. Don’t assume a localized name like a month abbreviation parses identically everywhere.

6. Error handling

Treat ValueError as an expected outcome for malformed, impossible, or mismatched input. Catch it where untrusted data enters your program:

from datetime import datetime

def parse_timestamp(text):
    try:
        return datetime.fromisoformat(text)
    except ValueError:
        return None  # or report the bad input

Quick decision guide

  • Input is ISO 8601 and your Python is 3.11+: fromisoformat().
  • Input is ISO-like but on an older Python, or uses an unsupported ISO form: strptime() with an explicit format.
  • Input is any other known pattern: strptime().
  • Input has no timezone information: you get a naive datetime, so decide what zone it represents.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.