Date arithmetic

2 snippets across 2 stacks — Python, SQL

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.

SQLSQL

Date Addition / Subtraction

SQL · Date Functions
syntax
-- PostgreSQL
date + INTERVAL 'n unit'
-- MySQL
DATE_ADD(date, INTERVAL n unit)
-- ANSI
date + INTERVAL 'n' unit
example
-- PostgreSQL
SELECT
  order_date,
  order_date + INTERVAL '30 days' AS due_date,
  order_date - INTERVAL '1 year' AS year_ago
FROM orders;

-- MySQL
SELECT
  order_date,
  DATE_ADD(order_date, INTERVAL 30 DAY) AS due_date
FROM orders;
output
-- order_date  | due_date    | year_ago
-- 2025-10-15  | 2025-11-14  | 2024-10-15

Note Interval units: YEAR, MONTH, DAY, HOUR, MINUTE, SECOND. Adding months is tricky — Jan 31 + 1 month may yield Feb 28 or Mar 3 depending on the database. PostgreSQL truncates to end of month; MySQL may overflow.