Skip to content

Instantly share code, notes, and snippets.

@vadimkantorov
Last active July 3, 2026 12:58
Show Gist options
  • Select an option

  • Save vadimkantorov/11d8d4aaf5fb05e468afdea71e092c6b to your computer and use it in GitHub Desktop.

Select an option

Save vadimkantorov/11d8d4aaf5fb05e468afdea71e092c6b to your computer and use it in GitHub Desktop.
Python ISO8601 date (YYYY-MM-DD) regex and testing script, handling leap years
import datetime
import re
# https://regexlib.com/REDetails.aspx?regexp_id=3344&AspxAutoDetectCookieSupport=1
# http://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime/7221570#7221570
re_iso8601date = r'^(?:(?=[02468][048]00|[13579][26]00|[0-9][0-9]0[48]|[0-9][0-9][2468][048]|[0-9][0-9][13579][26])\d{4}(?:(-|)(?:(?:00[1-9]|0[1-9][0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-6])|(?:01|03|05|07|08|10|12)(?:\1(?:0[1-9]|[12][0-9]|3[01]))?|(?:04|06|09|11)(?:\1(?:0[1-9]|[12][0-9]|30))?|02(?:\1(?:0[1-9]|[12][0-9]))?|W(?:0[1-9]|[1-4][0-9]|5[0-3])(?:\1[1-7])?))?)$|^(?:(?![02468][048]00|[13579][26]00|[0-9][0-9]0[48]|[0-9][0-9][2468][048]|[0-9][0-9][13579][26])\d{4}(?:(-|)(?:(?:00[1-9]|0[1-9][0-9]|[1-2][0-9][0-9]|3[0-5][0-9]|36[0-5])|(?:01|03|05|07|08|10|12)(?:\2(?:0[1-9]|[12][0-9]|3[01]))?|(?:04|06|09|11)(?:\2(?:0[1-9]|[12][0-9]|30))?|(?:02)(?:\2(?:0[1-9]|1[0-9]|2[0-8]))?|W(?:0[1-9]|[1-4][0-9]|5[0-3])(?:\2[1-7])?))?)$'
for yyyy in range(1000, 3001):
for mm in range(1, 13):
for dd in range(1, 32):
yyyy_mm_dd = f'{yyyy:04d}-{mm:02d}-{dd:02d}'
re_valid = re.fullmatch(re_iso8601date, yyyy_mm_dd) is not None
valid = False
try:
datetime.date.fromisoformat(yyyy_mm_dd)
valid = True
except:
valid = False
assert valid == re_valid, yyyy_mm_dd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment