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.

Frequently asked questions

How does Python handle date arithmetic?
This task is covered in 2 stacks on this page: Python, SQL. The "datetime Module" snippet in Python uses `from datetime import datetime, date, timedelta`.
Which code does the Python example use?
The "datetime Module" snippet uses `from datetime import datetime, date, timedelta`, from the Common Standard Library section of the Python cheat sheet.
Which stacks cover "date arithmetic" on this page?
Python, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "datetime Module": For timezone-aware datetimes, use datetime.now(tz=timezone.utc) instead of datetime.utcnow() which is naive and deprecated since 3.12.