Database Money, Dates and Time Zones
What you will learn
- Why decimal fractions are risky as floating-point numbers
- How to store money safely (whole minor units)
- How to store a moment in time (UTC) and show local time
- How SQLite stores dates (as text) and what that means
Two kinds of data cause more silent bugs than any other: money and time. The SQL examples run on the sample database you chose in lesson 4.1 (use the Example data picker at the top). Some create small tables of their own in your browser's copy; Reset data removes them. Run the examples from top to bottom.
1. Money and floating point
Computers store a REAL (floating-point) number in binary, and most decimal fractions such as 0.1 cannot be written exactly in binary. The tiny errors show up when you compare or add. Python shows it first:
total = 0.0
for _ in range(10):
total += 0.1
print(total, total == 1.0)
print(0.1 + 0.2 == 0.3, round(0.1 + 0.2, 2) == 0.3)
0.9999999999999999 False
False True
Ten tenths do not make exactly one. SQLite gives the same answer as Python:
SELECT 0.1 + 0.2 AS total, 0.1 + 0.2 = 0.3 AS is_equal;
total is_equal
------------------- --------
0.30000000000000004 0
(1 row)
The same happens with real prices (a REAL column). Here are some products whose price plus 10% tax carries a long tail of digits:
SELECT product_id, price, price * 1.1 AS with_tax FROM products WHERE price * 1.1 <> ROUND(price * 1.1, 2) ORDER BY product_id LIMIT 4;
product_id price with_tax
---------- ----- ------------------
2 44.1 48.510000000000005
4 5.4 5.940000000000001
8 20.9 22.990000000000002
9 35.1 38.61000000000001
(4 rows)
SELECT 0.1 + 0.2 AS total, 0.1 + 0.2 = 0.3 AS is_equal;
total is_equal
------------------- --------
0.30000000000000004 0
(1 row)
The bank avoids the problem: its balances are whole cents in an INTEGER column (balance_cents), never a REAL. Section 2 shows that design.
SELECT 0.1 + 0.2 AS total, 0.1 + 0.2 = 0.3 AS is_equal;
total is_equal
------------------- --------
0.30000000000000004 0
(1 row)
The same happens with real grades (a REAL column). Here are some grades whose 10% boost carries a long tail of digits:
SELECT student_id, section_id, grade, grade * 1.1 AS boosted FROM enrollments WHERE grade IS NOT NULL AND grade * 1.1 <> ROUND(grade * 1.1, 1) ORDER BY student_id, section_id LIMIT 4;
student_id section_id grade boosted
---------- ---------- ----- ------------------
1 30 49.2 54.120000000000005
1 41 60.8 66.88
2 6 55.3 60.83
2 9 80.4 88.44000000000001
(4 rows)
0.1 + 0.2 = 0.3 is false. (Some functions, such as SQLite's SUM, add more carefully and can hide the error, so a test that happens to pass proves little.) For a shop total an error of a hundred-trillionth is invisible, but equality checks ("is the paid amount equal to the price?") can fail.
Quick check: Why is a `float` a poor type for storing money?
Binary floating point cannot represent many decimal amounts exactly, so tiny errors appear and add up. Whole minor units (such as cents) in an integer are exact.
2. The safe way: whole minor units
Store money as an integer count of the smallest unit (poisha, cents, pence), with a currency noted somewhere:
CREATE TABLE gift_cards (code TEXT PRIMARY KEY, balance_cents INTEGER NOT NULL CHECK (balance_cents >= 0));
INSERT INTO gift_cards VALUES ('GC-001', 1999);
SELECT balance_cents * 3 AS three_cards, balance_cents * 3 = 5997 AS is_exact,
printf('%d.%02d', balance_cents * 3 / 100, balance_cents * 3 % 100) AS shown
FROM gift_cards;
three_cards is_exact shown
----------- -------- -----
5997 1 59.97
(1 row)
SELECT account_id, balance_cents, printf('%d.%02d', balance_cents / 100, balance_cents % 100) AS shown
FROM accounts ORDER BY account_id LIMIT 3;
SELECT SUM(balance_cents) AS total_cents, printf('%d.%02d', SUM(balance_cents) / 100, SUM(balance_cents) % 100) AS total_shown FROM accounts;
account_id balance_cents shown
---------- ------------- -------
1 192400 1924.00
2 52078 520.78
3 62780 627.80
(3 rows)
total_cents total_shown
----------- -----------
62199130 621991.30
(1 row)
CREATE TABLE trip_fees (fee_id INTEGER PRIMARY KEY, name TEXT NOT NULL, amount_cents INTEGER NOT NULL CHECK (amount_cents >= 0));
INSERT INTO trip_fees (name, amount_cents) VALUES ('Museum trip', 1999);
SELECT amount_cents * 3 AS three_students, amount_cents * 3 = 5997 AS is_exact,
printf('%d.%02d', amount_cents * 3 / 100, amount_cents * 3 % 100) AS shown
FROM trip_fees;
three_students is_exact shown
-------------- -------- -----
5997 1 59.97
(1 row)
Integers are exact, so equality works. Only format with a decimal point when showing the amount (printf('%d.%02d', cents / 100, cents % 100) does it here). Python's decimal.Decimal is another exact choice in code (Decimal(1999) / 100 gives 19.99), and many database systems have an exact DECIMAL/NUMERIC type; SQLite does not truly store exact decimals, so whole units are the dependable way there. Check your own system's documentation for its exact type.
Three more habits:
- Keep the currency with the amount (a
currencycolumn, or one currency per table by design). - Never convert between currencies by multiplying stored rounded values; store the rate and the date, and round once at the end by a stated rule.
- Decide the rounding rule (round half up? to even?) and apply it in one place.
3. Moments in time: store UTC
A moment (an order was placed, a user logged in) is one instant for the whole world. Local clocks differ: when it is 23:30 on 1 March in Dhaka (UTC+6), it is 17:30 in UTC. Python's datetime does the conversion:
from datetime import datetime, timezone, timedelta
dhaka = timezone(timedelta(hours=6))
local = datetime(2026, 3, 1, 23, 30, tzinfo=dhaka)
print(local.isoformat())
utc = local.astimezone(timezone.utc)
print(utc.isoformat(timespec="seconds"))
2026-03-01T23:30:00+06:00
2026-03-01T17:30:00+00:00
Rule: store moments in UTC, and convert to the viewer's local time only when displaying. Then rows from different countries sort and compare correctly, and daylight-saving changes cannot create duplicate or missing hours in your data.
SQLite has no date type. Dates and times are ordinary text (or numbers). The text form YYYY-MM-DD HH:MM:SS has a useful property: alphabetical order equals time order.
CREATE TABLE store_events (name TEXT, at_utc TEXT NOT NULL);
INSERT INTO store_events VALUES ('late shop close', '2026-03-01 17:30:00');
INSERT INTO store_events VALUES ('morning', '2026-03-01 04:00:00');
SELECT * FROM store_events ORDER BY at_utc;
SELECT name, datetime(at_utc, '+6 hours') AS dhaka_time FROM store_events ORDER BY at_utc;
SELECT typeof(at_utc) AS type, date(at_utc) AS day, strftime('%Y-%m', at_utc) AS month FROM store_events LIMIT 1;
name at_utc
--------------- -------------------
morning 2026-03-01 04:00:00
late shop close 2026-03-01 17:30:00
(2 rows)
name dhaka_time
--------------- -------------------
morning 2026-03-01 10:00:00
late shop close 2026-03-01 23:30:00
(2 rows)
type day month
---- ---------- -------
text 2026-03-01 2026-03
(1 row)
The real order dates are text too, and they group and sort correctly:
SELECT strftime('%Y-%m', order_date) AS month, COUNT(*) AS orders FROM orders GROUP BY month ORDER BY month LIMIT 4;
month orders
------- ------
2024-01 17
2024-02 18
2024-03 27
2024-04 24
(4 rows)
CREATE TABLE bank_events (name TEXT, at_utc TEXT NOT NULL);
INSERT INTO bank_events VALUES ('late branch close', '2026-03-01 17:30:00');
INSERT INTO bank_events VALUES ('morning', '2026-03-01 04:00:00');
SELECT * FROM bank_events ORDER BY at_utc;
SELECT name, datetime(at_utc, '+6 hours') AS dhaka_time FROM bank_events ORDER BY at_utc;
SELECT typeof(at_utc) AS type, date(at_utc) AS day, strftime('%Y-%m', at_utc) AS month FROM bank_events LIMIT 1;
name at_utc
----------------- -------------------
morning 2026-03-01 04:00:00
late branch close 2026-03-01 17:30:00
(2 rows)
name dhaka_time
----------------- -------------------
morning 2026-03-01 10:00:00
late branch close 2026-03-01 23:30:00
(2 rows)
type day month
---- ---------- -------
text 2026-03-01 2026-03
(1 row)
The real ledger dates are text too, and they group and sort correctly:
SELECT strftime('%Y-%m', txn_date) AS month, COUNT(*) AS entries FROM transactions GROUP BY month ORDER BY month LIMIT 4;
month entries
------- -------
2018-02 2
2018-03 5
2018-04 6
2018-05 7
(4 rows)
CREATE TABLE school_events (name TEXT, at_utc TEXT NOT NULL);
INSERT INTO school_events VALUES ('late class ends', '2026-03-01 17:30:00');
INSERT INTO school_events VALUES ('morning', '2026-03-01 04:00:00');
SELECT * FROM school_events ORDER BY at_utc;
SELECT name, datetime(at_utc, '+6 hours') AS dhaka_time FROM school_events ORDER BY at_utc;
SELECT typeof(at_utc) AS type, date(at_utc) AS day, strftime('%Y-%m', at_utc) AS month FROM school_events LIMIT 1;
name at_utc
--------------- -------------------
morning 2026-03-01 04:00:00
late class ends 2026-03-01 17:30:00
(2 rows)
name dhaka_time
--------------- -------------------
morning 2026-03-01 10:00:00
late class ends 2026-03-01 23:30:00
(2 rows)
type day month
---- ---------- -------
text 2026-03-01 2026-03
(1 row)
The real due dates are text too, and they group and sort correctly:
SELECT strftime('%Y-%m', due_date) AS month, COUNT(*) AS assignments FROM assignments GROUP BY month ORDER BY month LIMIT 4;
month assignments
------- -----------
2025-02 7
2025-03 28
2025-04 28
2025-05 5
(4 rows)
The second query shows Dhaka time by adding six hours. Real programs should convert with a proper time zone library, because the offset is not always fixed (some places change it with daylight saving). Other database systems have real date and timestamp types, and some have a type that remembers the zone conversion; their rules differ, so read your system's documentation.
Invalid dates: a text column accepts any text, and the date functions return NULL for nonsense instead of failing:
SELECT date('2026-13-01') AS month_13, date('not a date') AS nonsense;
month_13 nonsense
-------- --------
NULL NULL
(1 row)
SELECT date('2026-13-01') AS month_13, date('not a date') AS nonsense;
month_13 nonsense
-------- --------
NULL NULL
(1 row)
SELECT date('2026-13-01') AS month_13, date('not a date') AS nonsense;
month_13 nonsense
-------- --------
NULL NULL
(1 row)
Some nonsense is even repaired quietly. In Python's SQLite 3.50.4, date('2026-02-30') turns into 2 March:
import sqlite3
con = sqlite3.connect(":memory:")
print(con.execute("SELECT date('2026-02-30'), date('2026-13-01')").fetchone())
('2026-03-02', None)
The older SQLite inside the browser, 3.39.0, returns 2026-02-30 unchanged for that date, so the two versions differ (lesson 1.7); either way the database does not complain. Validate dates in your program or with CHECK constraints.
4. Dates without a time
A birthday or due date is a calendar date, not a moment. Store it as YYYY-MM-DD and do not convert it to UTC; it does not shift when the viewer travels.
Worked example: an order system
| Field | Meaning | Store as |
|---|---|---|
total_cents |
amount | integer, e.g. 5997 |
currency |
which money | text BDT |
placed_at_utc |
moment the order was placed | 2026-03-01 17:30:00 (UTC) |
delivery_date |
the day the customer wants it | 2026-03-05 (a date) |
A customer in Dhaka places the order at 23:30 on 1 March. The database holds 17:30 UTC; the web page shows 1 March 23:30 in Dhaka. The delivery date 2026-03-05 is shown as is. The data is made up.
Common mistakes
- Using
REALfor money and comparing with=. - Storing local time without noting the zone, then mixing it with other zones.
- Storing dates in free formats (
3/4/26: March or April?). Use ISO formYYYY-MM-DD. - Converting calendar dates to UTC, which can move a birthday by a day.
- Trusting the database to reject bad dates. SQLite will not.
Key takeaways
- Binary floating point cannot hold most decimals exactly; do not use it for money.
- Store money as whole minor units (or an exact decimal type), with a currency.
- Store moments in UTC; convert to local time only to display.
- Store calendar dates as ISO
YYYY-MM-DDtext (SQLite has no date type). - Validate dates yourself; SQLite will accept nonsense text.
Practice
1. Why is 0.1 + 0.2 = 0.3 false?
Show answer
Binary floating point cannot represent 0.1 or 0.2 exactly, so the sum is 0.30000000000000004, not exactly 0.3.
2. A product costs 49.50 taka. How do you store it?
Show answer
As the integer 4950 (poisha) in a column such as price_poisha, with the currency known.
3. What time is stored in UTC for 09:00 on 5 May in Dhaka (UTC+6)?
Show answer
03:00 on 5 May UTC.
4. Why does YYYY-MM-DD HH:MM:SS text sort correctly?
Show answer
The biggest unit comes first and every part has fixed width, so alphabetical order equals time order.
5. Should a birthday be stored in UTC? Why or why not?
Show answer
No. A birthday is a calendar date, not a moment; converting it could move it by a day.
6. In the lesson, what did SQLite 3.50.4 do with date('2026-02-30'), and what should you do about it?
Show answer
It turned it into 2026-03-02 without complaint. Validate dates in your program or with CHECK constraints.