Format date

4 snippets across 4 stacks — Bash & Linux, Python, Regular Expressions, SQL

Also written as date format · date_format

SHBash & Linux

Date & Time

SH · System Info
syntax
date [+format]
example
date
date '+%Y-%m-%d %H:%M:%S'
date -d '+7 days' '+%Y-%m-%d'
date -u
output
Sat Apr  4 14:22:01 UTC 2026
2026-04-04 14:22:01
2026-04-11

Note Common format tokens: %Y (year), %m (month), %d (day), %H (hour), %M (minute), %S (second), %s (Unix epoch). -d adjusts the date (GNU only; on macOS use -v). -u outputs UTC. Useful for timestamped filenames: backup_$(date +%Y%m%d_%H%M%S).tar.gz.

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.

RXRegular Expressions

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.

SQLSQL

Date Formatting

SQL · Date Functions
syntax
-- PostgreSQL
TO_CHAR(date, 'format')
-- MySQL
DATE_FORMAT(date, 'format')
example
-- PostgreSQL
SELECT TO_CHAR(order_date, 'YYYY-MM-DD') AS iso_date,
       TO_CHAR(order_date, 'Mon DD, YYYY') AS pretty_date
FROM orders;

-- MySQL
SELECT DATE_FORMAT(order_date, '%Y-%m-%d') AS iso_date,
       DATE_FORMAT(order_date, '%b %d, %Y') AS pretty_date
FROM orders;
output
-- iso_date    | pretty_date
-- 2025-10-15  | Oct 15, 2025

Note Format codes differ between databases. PostgreSQL uses YYYY, MM, DD, HH24, MI, SS. MySQL uses %Y, %m, %d, %H, %i, %s. Format dates in the application layer when possible to avoid DB-specific code.