October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

Convert Strings to Dates in Python: `date`, `datetime`, and `strptime()`

Use `date.fromisoformat()` for supported ISO dates, `datetime.fromisoformat()` for timestamps, and `strptime()` for a known custom layout.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the parser based on both the input format and the Python type you need: use date.fromisoformat() for a supported ISO calendar date, datetime.fromisoformat() for a supported ISO timestamp, and strptime() when a known custom layout needs an explicit format string. Parsing does not determine what an ambiguous date means, so confirm the source convention before converting it.

Choose the right parser and result type

Input Desired result Use Key consideration
Supported ISO date, such as 2024-07-15 date date.fromisoformat(value) Returns a calendar date; only documented ISO forms are accepted.
Supported ISO timestamp, such as 2024-07-15T09:30:00+00:00 datetime datetime.fromisoformat(value) Can retain supported time and timezone information.
Known custom date layout date date.strptime(value, format) The format must describe the input layout.
Known custom date-and-time layout datetime datetime.strptime(value, format) Format-code behavior can vary by platform.

These methods and their behavior are documented in the Python 3.14.7 datetime reference.

Parse an ISO date into a `date`

Use date.fromisoformat() when the value represents a calendar date without a time:

from datetime import date

value = "2024-07-15"
parsed_date = date.fromisoformat(value)

print(parsed_date)        # 2024-07-15
print(type(parsed_date))  # <class 'datetime.date'>

The method returns a date, which is appropriate for birthdays, due dates, or other values where a time of day is not part of the data. Documented inputs include the familiar YYYY-MM-DD form, compact YYYYMMDD, and ISO week dates.

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

Do not assume this method accepts every string that could be described as ISO. The documented exclusions include reduced-precision dates such as YYYY-MM or YYYY, extended signed six-digit years, and ordinal dates such as YYYY-OOO. Use the exact format accepted by the method, or parse a different known layout explicitly.

Parse an ISO timestamp into a `datetime`

For a supported ISO date-time string, use datetime.fromisoformat(). The result carries date and time fields and can carry timezone information when the input includes a supported timezone designator:

from datetime import datetime

value = "2024-07-15T09:30:00+00:00"
parsed_datetime = datetime.fromisoformat(value)

print(parsed_datetime)
print(parsed_datetime.tzinfo)

Supported examples include a trailing Z and numeric offsets such as +00:00. Preserve the distinction between a timestamp with timezone information and one without it: the parser does not infer a timezone for a string that omits one. The accepted forms have documented exceptions, so validate the specific input shape your source supplies.

Parse a known custom format with `strptime()`

For a non-ISO string, describe its layout with format directives. For example, %d is the day, %m the month, and %Y the four-digit year:

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

value = "15/07/2024"
parsed_datetime = datetime.strptime(value, "%d/%m/%Y")
print(parsed_datetime)  # 2024-07-15 00:00:00

If the input contains only a date and you want a date, use date.strptime() where available:

from datetime import date

value = "15/07/2024"
parsed_date = date.strptime(value, "%d/%m/%Y")
print(parsed_date)  # 2024-07-15

A format mismatch raises ValueError. Catch it when invalid or unexpected input is a normal possibility:

from datetime import datetime

value = "31/02/2024"

try:
    parsed = datetime.strptime(value, "%d/%m/%Y")
except ValueError as error:
    print(f"Invalid date: {error}")

Choose the format from the data contract, not merely from how one sample looks. For instance, 03/04/2024 could mean 3 April or March 4 depending on the source convention; a format string makes the convention explicit but cannot tell you which convention the source intended.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle partial dates and Python-version differences

Month and day without a year

A format that parses a day and month but omits the year relies on a default year that is not a leap year. As a result, a value such as February 29 cannot be safely parsed that way. If the source omits the year, supply an explicit year before parsing; the Python documentation illustrates using 1984, a leap year, for this purpose.

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

Python 3.13 added a deprecation warning for datetime.strptime() formats that specify a day without a year. The documentation says these forms may raise an error in Python 3.15. If the data has a year, include it in the format and input. If the year is genuinely absent, define how to supply or represent it rather than silently relying on a default.

`fromisoformat()` support

Python 3.11 broadened the accepted inputs for both date.fromisoformat() and datetime.fromisoformat(). In earlier releases, support was narrower: the date method was limited to YYYY-MM-DD, and the datetime method was limited to forms that could be emitted by isoformat(). If code must run on older Python versions, constrain inputs to forms supported by those versions or check the relevant version’s documentation.

Platform variation in format codes

strptime() relies on the platform C library for format-code support and behavior, so some codes can vary across platforms. When portability matters, favor widely supported directives and test the formats on the operating systems and Python versions where the code will run.

Validate the result for the task

  • Use date when time-of-day information is irrelevant; use datetime when it matters.
  • Use an ISO parser only for an input shape it documents as supported.
  • For custom layouts, specify the source’s actual ordering and separators in the format string.
  • Handle ValueError for malformed or impossible dates rather than assuming conversion always succeeds.
  • For timestamps, check whether timezone information is present and meaningful for subsequent comparisons or calculations.

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.

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

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
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.