ZetCode

Python parse dates

last modified November 19, 2026 Python 3.15

In this article we turn strings into date and datetime objects. Python's standard library offers two tools: strptime, which reads any format described by directives, and fromisoformat, which reads ISO 8601 strings.

The opposite direction, turning dates into strings, is covered in Python format datetime, and the date types themselves in Python datetime. The examples run with the TZ environment variable set to Europe/Bratislava.

A first parse

The datetime.strptime method takes a string and a format. The format uses the same directives as strftime: %d for the day, %m for the month, %Y for the four-digit year, %H and %M for hours and minutes.

first_parse.py
from datetime import datetime

text = "19.11.2026 14:30"
dt = datetime.strptime(text, "%d.%m.%Y %H:%M")

print(dt)
print(repr(dt))
print(dt.year, dt.month, dt.day)

Characters that are not directives, here the dots, the space, and the colon, must appear in the string exactly as in the format. The result is a naive datetime.

$ python first_parse.py
2026-11-19 14:30:00
datetime.datetime(2026, 11, 19, 14, 30)
2026 11 19

Reading the errors

When the string and the format do not fit together, strptime raises ValueError. The message tells what went wrong.

parse_errors.py
from datetime import datetime

cases = [
    ("2026-11-19", "%Y-%m-%d"),
    ("2026-11-19 14:30", "%Y-%m-%d"),
    ("2026/11/19", "%Y-%m-%d"),
    ("2026-02-30", "%Y-%m-%d"),
    ("2026-1-5", "%Y-%m-%d"),
    ("  2026-11-19", "%Y-%m-%d"),
    ("19 Nov 2026", "%d %b %Y"),
    ("19 november 2026", "%d %B %Y"),
]

for text, fmt in cases:
    try:
        print(f"{text!r:22} {datetime.strptime(text, fmt)}")
    except ValueError as e:
        print(f"{text!r:22} ValueError: {e}")

The whole string must be consumed: extra text after the date gives unconverted data remains, and a different separator or a leading space gives does not match format. A date that matches the format but does not exist fails in the date constructor. Some rules are lenient: %m and %d accept one digit, and month names are matched without regard to case.

$ python parse_errors.py
'2026-11-19'           2026-11-19 00:00:00
'2026-11-19 14:30'     ValueError: unconverted data remains:  14:30
'2026/11/19'           ValueError: time data '2026/11/19' does not match format '%Y-%m-%d'
'2026-02-30'           ValueError: day 30 must be in range 1..28 for month 2 in year 2026
'2026-1-5'             2026-01-05 00:00:00
'  2026-11-19'         ValueError: time data '  2026-11-19' does not match format '%Y-%m-%d'
'19 Nov 2026'          2026-11-19 00:00:00
'19 november 2026'     2026-11-19 00:00:00

date.strptime and time.strptime

Before Python 3.14, strptime existed only on the datetime class, and we called date on the result. Python 3.14 added date.strptime and time.strptime.

date_time_strptime.py
import sys
from datetime import date, time

print(sys.version.split()[0])

try:
    print(date.strptime("19.11.2026", "%d.%m.%Y"))
    print(time.strptime("14:30", "%H:%M"))
except AttributeError as e:
    print("AttributeError:", e)

The new methods return a date or a time directly. On Python 3.13 the attribute does not exist. The time.strptime method of the datetime module is a different function from strptime in the time module, which returns a struct_time.

$ python date_time_strptime.py
3.15.2
2026-11-19
14:30:00
$ python3.13 date_time_strptime.py
3.13.11
AttributeError: type object 'datetime.date' has no attribute 'strptime'

ISO 8601 strings

For ISO 8601 strings, fromisoformat is simpler and faster than strptime. Since Python 3.11 it accepts most of the standard.

iso_formats.py
from datetime import date, datetime, time

samples = [
    "2026-11-19",
    "2026-11-19T14:30",
    "2026-11-19 14:30:05.250",
    "2026-11-19T14:30:05,250",
    "2026-11-19T14:30:05Z",
    "2026-11-19T14:30:05+01:00",
    "20261119T143005",
    "2026-W47-4",
    "2026-11-19T24:00",
    "19.11.2026",
]

for text in samples:
    try:
        print(f"{text:26} {datetime.fromisoformat(text)!r}")
    except ValueError as e:
        print(f"{text:26} ValueError: {e}")

print(date.fromisoformat("2026-11-19"))
print(time.fromisoformat("14:30:05.25"))

The method accepts a space or T between date and time, a fraction with a dot or a comma, the Z suffix for UTC, UTC offsets, the basic format without separators, and ISO week dates. Python 3.14 added 24:00, which means midnight at the end of the day. Strings in other formats raise ValueError. The date and time classes have their own fromisoformat. The method is implemented in C and is many times faster than strptime, which interprets its format in Python code; store dates in ISO 8601 when you control the format.

$ python iso_formats.py
2026-11-19                 datetime.datetime(2026, 11, 19, 0, 0)
2026-11-19T14:30           datetime.datetime(2026, 11, 19, 14, 30)
2026-11-19 14:30:05.250    datetime.datetime(2026, 11, 19, 14, 30, 5, 250000)
2026-11-19T14:30:05,250    datetime.datetime(2026, 11, 19, 14, 30, 5, 250000)
2026-11-19T14:30:05Z       datetime.datetime(2026, 11, 19, 14, 30, 5, tzinfo=datetime.timezone.utc)
2026-11-19T14:30:05+01:00  datetime.datetime(2026, 11, 19, 14, 30, 5, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600)))
20261119T143005            datetime.datetime(2026, 11, 19, 14, 30, 5)
2026-W47-4                 datetime.datetime(2026, 11, 19, 0, 0)
2026-11-19T24:00           datetime.datetime(2026, 11, 20, 0, 0)
19.11.2026                 ValueError: Invalid isoformat string: '19.11.2026'
2026-11-19
14:30:05.250000

Trying several formats

Input from users or old files often mixes formats. A common solution tries a list of formats until one fits.

several_formats.py
from datetime import datetime

FORMATS = [
    "%Y-%m-%d",
    "%d.%m.%Y",
    "%d %b %Y",
    "%B %d, %Y",
    "%Y%m%d",
]


def parse_date(text):
    text = text.strip()
    try:
        return datetime.fromisoformat(text).date()
    except ValueError:
        pass
    for fmt in FORMATS:
        try:
            return datetime.strptime(text, fmt).date()
        except ValueError:
            continue
    raise ValueError(f"unknown date format: {text!r}")


inputs = ["2026-11-19", " 19.11.2026", "19 Nov 2026", "November 19, 2026",
          "20261119", "2026-11-19T08:00", "11/19/2026"]

for text in inputs:
    try:
        print(f"{text!r:22} {parse_date(text)}")
    except ValueError as e:
        print(e)

The parse_date function tries fromisoformat first, then each format in turn. The order of the list matters when a string fits two formats. The US form 11/19/2026 is not in the list, so it is rejected rather than guessed.

$ python several_formats.py
'2026-11-19'           2026-11-19
' 19.11.2026'          2026-11-19
'19 Nov 2026'          2026-11-19
'November 19, 2026'    2026-11-19
'20261119'             2026-11-19
'2026-11-19T08:00'     2026-11-19
unknown date format: '11/19/2026'

UTC offsets and zone abbreviations

The %z directive parses a UTC offset and produces an aware datetime. The %Z directive parses a time zone name, with restrictions.

offsets.py
from datetime import datetime

samples = [
    ("2026-11-19 14:30 +0100", "%Y-%m-%d %H:%M %z"),
    ("2026-11-19 14:30 -05:00", "%Y-%m-%d %H:%M %z"),
    ("2026-11-19 14:30 Z", "%Y-%m-%d %H:%M %z"),
    ("2026-11-19 14:30 UTC", "%Y-%m-%d %H:%M %Z"),
    ("2026-11-19 14:30 CET", "%Y-%m-%d %H:%M %Z"),
    ("2026-11-19 14:30 EST", "%Y-%m-%d %H:%M %Z"),
]

for text, fmt in samples:
    try:
        dt = datetime.strptime(text, fmt)
        print(f"{text:24} {dt}  tzinfo={dt.tzinfo!r}")
    except ValueError as e:
        print(f"{text:24} ValueError: {e}")

a = datetime.strptime("2026-11-19 14:30 +0100", "%Y-%m-%d %H:%M %z")
b = datetime.strptime("2026-11-19 08:30 -05:00", "%Y-%m-%d %H:%M %z")
print(a == b, a - b)

The %z directive accepts +0100, -05:00, and Z, and attaches a fixed-offset timezone. The %Z directive accepts only UTC, GMT, and the names of the local time zone, CET and CEST here; other abbreviations such as EST fail. Even a matched name leaves the result naive. Abbreviations are ambiguous anyway: IST is used in India, Ireland, and Israel. The two aware datetimes describe the same moment, so they are equal.

$ python offsets.py
2026-11-19 14:30 +0100   2026-11-19 14:30:00+01:00  tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))
2026-11-19 14:30 -05:00  2026-11-19 14:30:00-05:00  tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=68400))
2026-11-19 14:30 Z       2026-11-19 14:30:00+00:00  tzinfo=datetime.timezone.utc
2026-11-19 14:30 UTC     2026-11-19 14:30:00  tzinfo=None
2026-11-19 14:30 CET     2026-11-19 14:30:00  tzinfo=None
2026-11-19 14:30 EST     ValueError: time data '2026-11-19 14:30 EST' does not match format '%Y-%m-%d %H:%M %Z'
True 0:00:00

Time zone names

To parse a time with an IANA time zone name, we parse the date and time part and attach a ZoneInfo object.

zone_names.py
from datetime import UTC, datetime
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError


def parse_zoned(text):
    stamp, name = text.rsplit(" ", 1)
    naive = datetime.strptime(stamp, "%Y-%m-%d %H:%M")
    return naive.replace(tzinfo=ZoneInfo(name))


events = [
    "2026-11-19 09:00 America/New_York",
    "2026-11-19 15:00 Europe/Bratislava",
    "2026-11-20 08:00 Asia/Tokyo",
    "2026-11-19 10:00 Mars/Olympus",
]

for text in events:
    try:
        dt = parse_zoned(text)
    except ZoneInfoNotFoundError as e:
        print("unknown zone:", e)
        continue
    print(f"{dt:%Y-%m-%d %H:%M %Z}  ->  {dt.astimezone(UTC):%Y-%m-%d %H:%M %Z}")

The rsplit call separates the zone name from the rest. The replace method attaches the zone without converting; the zone then decides the offset for that date, including daylight saving time. An unknown name raises ZoneInfoNotFoundError. See Python zoneinfo for details.

$ python zone_names.py
2026-11-19 09:00 EST  ->  2026-11-19 14:00 UTC
2026-11-19 15:00 CET  ->  2026-11-19 14:00 UTC
2026-11-20 08:00 JST  ->  2026-11-19 23:00 UTC
unknown zone: 'No time zone found with key Mars/Olympus'

Ambiguous dates and two-digit years

The string 01/02/03 can mean three different dates. A two-digit year adds another question: which century?

ambiguous.py
from datetime import datetime

text = "01/02/03"

for fmt, region in [("%m/%d/%y", "US"), ("%d/%m/%y", "Europe"),
                    ("%y/%m/%d", "ISO-like")]:
    print(f"{region:9} {datetime.strptime(text, fmt):%Y-%m-%d}")

for yy in ["00", "38", "68", "69", "99"]:
    print(yy, datetime.strptime(yy, "%y").year)


def fix_century(dt, today):
    if dt.year > today.year:
        return dt.replace(year=dt.year - 100)
    return dt


today = datetime(2026, 11, 19)
born = datetime.strptime("12.05.45", "%d.%m.%y")
print(born.date(), fix_century(born, today).date())

The format alone decides the meaning, so the program must know where the data comes from. The %y directive maps 69–99 to the 1900s and 00–68 to the 2000s, following POSIX. For birth dates that rule gives 2045, so fix_century moves dates in the future back by 100 years.

$ python ambiguous.py
US        2003-01-02
Europe    2003-02-01
ISO-like  2001-02-03
00 2000
38 2038
68 2068
69 1969
99 1999
2045-05-12 1945-05-12

Month and day names

The %B, %b, and %A directives match names in the language of the current LC_TIME locale.

month_names.py
import locale
from datetime import datetime

texts = [("19 November 2026", "%d %B %Y"),
         ("19. november 2026", "%d. %B %Y"),
         ("19. novembra 2026", "%d. %B %Y"),
         ("štvrtok 19. nov 2026", "%A %d. %b %Y")]


def try_all():
    for text, fmt in texts:
        try:
            print(f"  {text:22} {datetime.strptime(text, fmt):%Y-%m-%d}")
        except ValueError:
            print(f"  {text:22} no match")


print(locale.setlocale(locale.LC_TIME))
try_all()

print(locale.setlocale(locale.LC_TIME, "sk_SK.UTF-8"))
try_all()

locale.setlocale(locale.LC_TIME, "C")

In the default C locale, only English names match. After switching to the Slovak locale with setlocale, the Slovak weekday and short month name match too. The phrase 19. novembra still fails: Slovak uses the genitive form of the month in dates, while the locale provides the nominative november. Locale-based parsing also changes global state, which is not thread-safe, so the program switches back at the end. For dates in many languages, the dateparser library is a better choice.

$ python month_names.py
C
  19 November 2026       2026-11-19
  19. november 2026      2026-11-19
  19. novembra 2026      no match
  štvrtok 19. nov 2026   no match
sk_SK.UTF-8
  19 November 2026       2026-11-19
  19. november 2026      2026-11-19
  19. novembra 2026      no match
  štvrtok 19. nov 2026   2026-11-19

Leap day without a year

A format with a day of the month but no year, such as %b %d, is a trap: the missing year defaults to 1900, which was not a leap year. Python 3.15 changed how such formats behave.

leap_day.py
import sys
import warnings
from datetime import datetime

print(sys.version.split()[0])

for text in ["Nov 19", "Feb 29"]:
    with warnings.catch_warnings(record=True) as caught:
        warnings.simplefilter("always")
        try:
            result = datetime.strptime(text, "%b %d")
        except ValueError as e:
            result = "ValueError: " + str(e).split(". ")[0]
    note = "  + DeprecationWarning" if caught else ""
    print(f"  {text}: {result}{note}")

print(" ", datetime.strptime("2028 Feb 29", "%Y %b %d").date())

Python 3.14 parses Nov 19 as a date in 1900 with a DeprecationWarning, and fails on Feb 29, so a birthday list breaks only on leap-day entries. Python 3.15 raises ValueError for every such format. The fix is to put a year into both the string and the format. The catch_warnings block records the warning instead of printing it.

$ python leap_day.py
3.15.2
  Nov 19: ValueError: Day of month directive '%d' may not be used without a year directive
  Feb 29: ValueError: Day of month directive '%d' may not be used without a year directive
  2028-02-29
$ python3.14 leap_day.py
3.14.0
  Nov 19: 1900-11-19 00:00:00  + DeprecationWarning
  Feb 29: ValueError: day 29 must be in range 1..28 for month 2 in year 1900
  2028-02-29

Validating user input

Parsing is the first step of validation. A date can be well-formed and still be wrong for the purpose, such as a birth date in the future.

validate_input.py
from datetime import date, datetime


def read_birth_date(text, today):
    try:
        born = datetime.strptime(text.strip(), "%d.%m.%Y").date()
    except ValueError:
        return None, "use the DD.MM.YYYY format"
    if born > today:
        return None, "the date is in the future"
    if born.year < 1900:
        return None, "the date is too old"
    return born, None


today = date(2026, 11, 19)
inputs = ["12.05.1987", "31.04.1990", "1.2.2000", "05.12.2030",
          "17.03.1850", "1987-05-12", ""]

for text in inputs:
    born, error = read_birth_date(text, today)
    if error:
        print(f"{text!r:14} rejected: {error}")
    else:
        print(f"{text!r:14} accepted: {born}")

The function returns a date and an error message, one of which is None. April has 30 days, so 31.04.1990 fails in strptime just like a wrong format. After parsing, the range checks reject dates in the future and before 1900.

$ python validate_input.py
'12.05.1987'   accepted: 1987-05-12
'31.04.1990'   rejected: use the DD.MM.YYYY format
'1.2.2000'     accepted: 2000-02-01
'05.12.2030'   rejected: the date is in the future
'17.03.1850'   rejected: the date is too old
'1987-05-12'   rejected: use the DD.MM.YYYY format
''             rejected: use the DD.MM.YYYY format

Log timestamps

Web server logs store the time of each request in brackets. We extract the timestamps with a regular expression and parse them with %z.

log_times.py
import re
from collections import Counter
from datetime import UTC, datetime

STAMP = re.compile(r"\[([^\]]+)\]")

with open("access.log") as f:
    times = []
    for line in f:
        found = STAMP.search(line)
        if found:
            dt = datetime.strptime(found[1], "%d/%b/%Y:%H:%M:%S %z")
            times.append(dt)

print("first:", times[0])
print("first (UTC):", times[0].astimezone(UTC))
print("span:", times[-1] - times[0])

per_hour = Counter(dt.replace(minute=0, second=0) for dt in times)
for hour, count in sorted(per_hour.items()):
    print(f"{hour:%H:%M}  {'#' * count}")

The log file has the common format of Apache and nginx:

10.0.0.5 - - [19/Nov/2026:09:58:12 +0100] "GET / HTTP/1.1" 200 5120

The %b directive reads the month abbreviation and %z the offset, so the datetimes are aware and convert to UTC. Rounding each time down to the hour with replace groups the requests for the Counter.

$ python log_times.py
first: 2026-11-19 09:58:12+01:00
first (UTC): 2026-11-19 08:58:12+00:00
span: 2:06:58
09:00  #
10:00  ###
11:00  ##
12:00  #

Source

datetime – strftime() and strptime() behavior

datetime.fromisoformat

In this article we have parsed dates and times in Python. See also Python datetime, Python format datetime, Python zoneinfo, and Python ISO weeks.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.