Parse date

3 snippets across 2 stacks — Regular Expressions, Python

RXRegular Expressions

Capturing Group ()

RX · Groups & Alternation
syntax
(pattern)  captures the matched text
example
JS:  'Date: 2026-04-04'.match(/(\d{4})-(\d{2})-(\d{2})/)
Py:  m = re.search(r'(\d{4})-(\d{2})-(\d{2})', '2026-04-04')
     m.group(1), m.group(2), m.group(3)
output
JS: ["2026-04-04", "2026", "04", "04"]
Py: ('2026', '04', '04')

Note Each pair of parentheses creates a numbered capture group starting at 1. In JS, the full match is at index 0. Groups are essential for extracting parts of a match for later use.

Date Formats (YYYY-MM-DD / MM/DD/YYYY)

RX · Common Patterns
syntax
YYYY-MM-DD: /\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])/
MM/DD/YYYY: /(?:0[1-9]|1[0-2])\/(?:0[1-9]|[12]\d|3[01])\/\d{4}/
example
JS:  '2026-04-04 and 12/25/2025'.match(/\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01])/g)
Py:  re.findall(r'(?:0[1-9]|1[0-2])/(?:0[1-9]|[12]\d|3[01])/\d{4}', text)
output
JS: ["2026-04-04"]
Py: ["12/25/2025"]

Note Regex validates format but not logical correctness -- it will accept 02/31/2026 (Feb 31 does not exist). For actual date validation, parse the match with Date (JS) or datetime (Python) afterward.

PYPython

datetime Module

PY · Common Standard Library
syntax
from datetime import datetime, date, timedelta
example
from datetime import datetime, timedelta

now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))

deadline = now + timedelta(days=7, hours=3)
print(f"Due: {deadline:%B %d, %Y}")

parsed = datetime.strptime("2026-04-04", "%Y-%m-%d")
print(parsed.date())
output
2026-04-04 14:30
Due: April 11, 2026
2026-04-04

Note For timezone-aware datetimes, use datetime.now(tz=timezone.utc) instead of datetime.utcnow() which is naive and deprecated since 3.12.