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.

Frequently asked questions

How do you parse date?
This task is covered in 2 stacks on this page: Regular Expressions, Python. The "Capturing Group ()" snippet in Regular Expressions uses `(pattern) captures the matched text`.
Which pattern does the Regular Expressions example use?
The "Capturing Group ()" snippet uses `(pattern) captures the matched text`, from the Groups & Alternation section of the Regular Expressions cheat sheet.
Which stacks cover "parse date" on this page?
Regular Expressions, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Capturing Group ()": 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.