Standardising values: text, dates, addresses, phone numbers, units and currencies
TL;DR
Difficulty: Intermediate
Standardising gives every kind of value one agreed form, by a written rule, so counts, joins and sums stop splitting one thing into many.
- Keep the raw value, put the standard value beside it, and record a status. Unknown goes to quarantine, never to a default.
- Text: NFC, no invisible characters, single spaces. Compare with case folded match keys, store what the customer typed, fada included.
- Categories through a version controlled mapping table. Ireland is IE, and Northern Ireland is part of GB, never UK.
- Parse dates with explicit formats, store moments in UTC, and flag the hour that happens twice in October.
- Eircodes are text, phone numbers are E.164 with the delivery country as default region, lengths carry a unit.
- Money is an exact decimal with its currency, converted with a dated rate. Never add across currencies, and say whether VAT is included.
Ask the old address table how many countries a Limerick homeware shop ships to and it answers 41. The real number is five. This chapter shows how to give every kind of value one agreed form, from the fada and time zones to Eircodes, phone numbers, units and currencies, with tested code and worked numbers for each.
The same thing, written ten different ways
Ask a database a simple question, such as "how many countries do we ship to?", and you expect a short answer. At Shannonside Home, the invented online homeware shop in Limerick that this series follows, the honest answer from the old address table is 41. The shop ships to five countries. The other 36 "countries" are Ireland written as "Ireland", "ireland " with a trailing space, "Republic of Ireland", "ROI", "IRL", "IE", "Rep. of Ireland", a county typed into the country box ("Co. Clare") and a dozen more, plus the United Kingdom in seven spellings, plus a handful of typing slips.
Nothing in that table is missing, and nothing is duplicated in the sense of one customer stored twice. The problem is quieter. The same thing is written in different ways, so every count, every join and every filter splits one real thing into many pieces. That is what this chapter fixes.
Standardising means choosing one agreed form for every kind of value, and converting every incoming value to that form by a written rule. One country code per country. One format per Eircode or postal code. One way to store a phone number, a date, a time, a length, an amount of money. It sounds like tidying. In practice it decides whether your reports add up, whether your joins find their partners, and whether a parcel reaches the right door.
This chapter walks through every common kind of value in an online shop: free text, Unicode, file encodings, categories, dates, times and time zones, Eircodes and other postal codes, phone numbers, units, money, currencies, VAT and yes or no flags. Each one gets the rule, the trap that catches experienced engineers, a worked example from Shannonside Home, and code you can use. It assumes you have profiled your data and decided which problems to clean at all. If a term such as staging layer is new, the first chapter of this series explains it.
A quick reminder of the cast. Shannonside Home sells about 1,400 products at shannonsidehome.example. Niamh owns it. Callum is its developer and data engineer. The shop runs on Ruby on Rails and Solidus with PostgreSQL, and Callum loads everything into BigQuery in a European region, where dbt Core turns raw tables into clean ones. Around 1,980 orders a month, an average order value of €84 including VAT, five years of history, and data from GA4, Google Ads, Meta, Stripe, PayPal, a 3PL warehouse, supplier feeds, a newsletter tool and a spreadsheet Niamh keeps by hand. All of it is invented for the series.
Four rules that apply to every value
Before any technique, four rules. They are what separates standardising from silently rewriting your data.
- Keep the original. The raw value stays exactly as it arrived, in its own column or its own table. The standard value sits next to it. If a rule turns out to be wrong, you rerun it on the original. A later chapter in this series covers the raw, staging and clean layers that make this easy. For now, never overwrite.
- Write the rule down and put it in one place. A rule that lives in three dashboards is three rules that will drift apart. One function, one dbt model or one mapping table, tested, and recorded in the rule register from the chapter on when to clean.
- Never guess. If the rule cannot decide, the standard value stays empty and a status column says why. A guessed value looks exactly like a correct one, which is what makes it dangerous.
- Unknown goes to quarantine, never to a default. "Unknown" is a fact about your data. "Ireland" chosen because it is the most common answer is an invention. The chapter on missing data explains why an honest empty beats a convenient default.
Example: one address row, three columns per value
Here is one row from the legacy address table, the way Callum stages it. The raw columns are untouched. The standard columns are what the reports use. The status columns say how each standard value came about.
| Column | Raw | Standard | Status |
|---|---|---|---|
| Country | ireland (trailing space) | IE | mapped |
| Eircode | v94t9px | V94 T9PX | reshaped |
| Phone | 061 234 567 | +35361234567 | ok |
Three things follow from this layout. First, anyone can see what came in and what the pipeline made of it. Second, a wrong rule can be fixed and rerun without asking anyone to type the data again. Third, the status columns can be counted, which turns "the data is a bit messy" into "1.1% of phone numbers are missing", a number someone can act on.
Text: spaces you can see, and characters you cannot
Most standardising starts with plain text, because almost every other value arrives as text first. Three things go wrong with it.
Leading and trailing spaces. "Limerick" and "Limerick " are different strings to a computer. A GROUP BY city shows two cities. A join on email finds no partner. Trimming removes spaces at both ends.
Runs of spaces inside the value. "Niamh Walsh" with two spaces will not match "Niamh Walsh". Collapsing replaces every run of whitespace with a single space.
Characters you cannot see. These are the ones that cost an afternoon. A no break space (U+00A0) looks exactly like a space but is a different character, and it arrives whenever someone copies text from a web page or a word processor. A zero width space (U+200B) has no width at all. A byte order mark (U+FEFF) sits invisibly at the start of files saved by some Windows tools, and ends up glued to the first column name or the first value. A soft hyphen (U+00AD) is invisible unless a line breaks at it. None of them shows on screen. All of them break equality.
Case is the fourth issue, and it needs a decision rather than a rule. For display, keep the case the customer typed: "McDonald" must not become "Mcdonald". For matching, compare a folded version, so that "NIAMH@SHANNONSIDEHOME.EXAMPLE" finds "niamh@shannonsidehome.example". That gives you two different things: the display value and the match key. Store the display value. Compute the match key whenever you compare.
Example: the newsletter list that would not join
Callum joins the newsletter tool's export (38,000 subscribers) to the shop's customer table on email, to find out how many subscribers have ever bought. The first attempt matches 21,406 addresses. Niamh expected more.
Profiling the unmatched rows shows the reasons. 512 addresses carry a trailing space from the tool's export. 230 are in a different case from the shop's copy. 41 start with a byte order mark, because they were the first row of an old import file that someone opened and saved again. 9 contain a no break space where a customer had pasted their address from an email signature.
After trimming, removing the invisible characters and comparing case folded keys, the join matches 22,198 addresses: 792 more, a 3.7% rise in the number of subscribers known to have bought. Nothing about those customers changed. Only the comparison did.
Unicode: the same letter stored in two different ways
Here is a trap that catches experienced engineers. The "á" in "Siobhán" can be stored in two ways. One is a single character, "a with acute", the síneadh fada (U+00E1). The other is two characters: a plain "a" followed by a "combining acute accent" (U+0301), which the screen draws on top of the a. Both look identical. They are different strings. They have different lengths. They do not match. In a country where a good few names carry a fada, this is not an edge case.
The Unicode Standard calls these two forms canonically equivalent and defines normalisation forms to make them comparable1. The four forms:
| Form | What it does | Use it for |
|---|---|---|
| NFC | Composes: "a" plus combining acute becomes one "á" | Storing and displaying text. The safe default |
| NFD | Decomposes: one "á" becomes "a" plus combining acute | Rarely stored. Useful as a step before stripping accents for a match key |
| NFKC | Like NFC, plus "compatibility" folding: the ligature "fi" becomes "fi", a superscript "²" becomes "2" | Match keys only. It changes meaning, so never for display |
| NFKD | Like NFD, plus compatibility folding | Match keys only |
Where do decomposed characters come from? Text typed on some systems, file names from Apple devices, copy and paste from PDFs, and data that passed through a tool which decomposes. You will not see them until a join fails.
Case folding has its own surprise. Lower casing is not enough for caseless matching, because some letters change length when their case changes. The German "ß" has no traditional capital form, so "STRASSE" in capitals and "Straße" are the same word. Python documents this in its casefold() method: lower casing leaves "ß" alone, case folding turns it into "ss"2. Since 2017 the official German spelling rules also allow a capital "ẞ" (U+1E9E) alongside "SS"3, so a German address can now legitimately arrive in three forms. Shannonside Home ships the odd parcel to Germany, so this is not academic even in Limerick.
The rule that comes out of all this:
- Normalise every text column to NFC at the staging layer. It never changes what the reader sees.
- Build match keys with NFKC plus case folding, and use them only to compare.
- Never strip the fada from a stored name. "Seán" is not "Sean", and "Siobhán" is not "Siobhan". If a match needs accent insensitive comparison, do it in the match key.
Example: one customer called Siobhán, stored twice
The customer table holds two accounts for what is clearly one customer in Cork: "Siobhán Delaney", created on the website, and "Siobhán Delaney", created by the old platform's import. They look identical. A query for duplicates by name finds nothing. In Python:
import unicodedata
web = "Siobh\u00e1n Delaney" # one character for á
legacy = "Siobha\u0301n Delaney" # a followed by a combining acute accent
print(web == legacy) # False
print(len(web), len(legacy)) # 15 16
nfc = unicodedata.normalize("NFC", legacy)
print(nfc == web, len(nfc)) # True 15
print("Straße".casefold() == "STRASSE".casefold()) # True
The two strings differ by one character in length until both are in NFC. In the legacy import, Callum finds 1,184 names with decomposed characters. After NFC normalisation, 37 of them turn out to match an existing account exactly, and they join the duplicate review from the entity resolution chapter.
In SQL the same functions exist. PostgreSQL has normalize(text, form)4. BigQuery has NORMALIZE and NORMALIZE_AND_CASEFOLD, both defaulting to NFC5. For example:
-- BigQuery: a display value and a match key for customer names
select
customer_id,
normalize(full_name_raw, NFC) as full_name,
normalize_and_casefold(full_name_raw, NFKC) as full_name_key
from {{ ref('stg_shop__customers') }}
Encodings: when "Seán" arrives as "Seán"
Before a value can be standardised, the bytes in the file must be turned into characters correctly. That step is called decoding, and the rulebook it follows is the encoding. Almost everything modern uses UTF-8. Much older Windows software, and a great many warehouse management systems, still write Windows 1252 (Python calls it cp1252), which stores "á" as the single byte 0xE1.
Decode a Windows 1252 file as UTF-8, and the reader either fails on that byte or, if told to ignore errors, replaces the letter with a question mark in a diamond. Decode a UTF-8 file as Windows 1252, and you get the classic garbled text known as mojibake: "Seán" becomes "Seán", because the two bytes that UTF-8 uses for "á" are read as two separate characters. Once mojibake is saved and reloaded a second time, repairing it gets much harder, so the fix belongs at the very first read.
The rule: every source has a declared encoding, written in the loader, never guessed by a library. If a source changes encoding without notice, the loader should fail loudly, not carry on.
Example: the 3PL file
Shannonside Home's 3PL warehouse sends a daily CSV of shipments and returns. It is semicolon delimited and encoded in Windows 1252. One returned order belongs to a customer called Seán. Here is what happens to that name with the wrong setting and the right one:
name = "Seán"
as_utf8 = name.encode("utf-8")
print(as_utf8.decode("cp1252")) # Seán (mojibake)
as_cp1252 = name.encode("cp1252")
as_cp1252.decode("utf-8") # UnicodeDecodeError: byte 0xe1
Callum's loader states everything explicitly, including one setting that surprises people:
import pandas as pd
raw = pd.read_csv(
"3pl/returns_2026-10-26.csv",
sep=";",
encoding="cp1252",
dtype=str, # read every column as text, convert later on purpose
keep_default_na=False, # an empty cell stays "", and "NA" stays "NA"
)
Why keep_default_na=False? By default pandas turns a list of strings into missing values when it reads a file, including "NA", "N/A", "NULL", "None" and the empty string6. "NA" is also the ISO country code for Namibia, and "None" can be a real answer in a free text field. Reading everything as text and deciding later is slower to write and much faster to debug.
Categories: one country, many spellings, one mapping table
A category is a value drawn from a known, small set: a country, a payment method, a delivery service, a return reason. Categories are where the "41 countries" problem lives. The fix is a mapping table: one row per spelling you have seen, mapped to the one standard value.
For countries, the standard is ISO 3166, which gives every country a two letter code. Ireland is IE. Here is the trap for every Irish shop with customers north of the border: the code for the United Kingdom is GB, not UK, and Northern Ireland has no code of its own, because it is part of the United Kingdom. Germany is DE, Austria is AT, Switzerland is CH. The United Nations Statistics Division's country table lists these codes next to its own numeric codes, and it is a convenient public place to check them7. Solidus itself stores the two letter code in the iso column of spree_countries, and every address points to a country by country_id8. So the shop's own addresses are already clean. The trouble comes from data that never went through Solidus: the import from the old platform, the 3PL's file, the spreadsheet.
Three practical points make a mapping table work:
- Map match keys, not raw spellings. Build the key the same way on both sides (NFKC, case folded, spaces collapsed), so "Ireland", "ireland " and "IRELAND" all need a single row.
- Keep the table in version control. In dbt, a small CSV in the
seedsfolder becomes a table withdbt seed, and models refer to it withref(). The dbt documentation names exactly this use, a mapping of country codes, as a good seed, and warns against using seeds for raw data9. - Unmapped means quarantine. A new spelling leaves the standard value empty and the status says "unmapped". A test counts those rows, and a person adds the new spelling to the table. Over a few weeks the table stops growing.
Some spellings cannot be mapped on their own. "Ireland" usually means the Republic of Ireland, code IE. But a customer in Newry or Belfast may also write "Ireland", and both are in Northern Ireland, which is part of the United Kingdom, code GB. The value alone cannot decide. A cross field rule can: Northern Ireland postal codes start with "BT". That rule belongs in the model, written down and tested, not in someone's head.
Example: 41 spellings become five codes
The legacy address table holds 21,640 addresses from the old platform. Callum counts the distinct country spellings, maps them, and counts again.
| Standard code | Spellings before | Addresses |
|---|---|---|
| IE | 24 | 19,870 |
| GB | 7 | 1,212 |
| FR | 3 | 240 |
| DE | 3 | 198 |
| NL | 2 | 96 |
| Unmapped | 2 | 24 |
| Total | 41 | 21,640 |
The two unmapped spellings are an empty string and "n/a". Those 24 addresses go to quarantine, and since each belongs to an old order with an address, Callum can resolve most of them by hand in an hour. The county typed into the country box gets its own rows in the table ("co. clare" maps to IE), because it is unambiguous. Then the BT rule runs: 46 addresses mapped to IE have a postal code starting with "BT", so they are corrected to GB and marked with the status corrected_by_postcode. The final count is 19,824 addresses in IE and 1,258 in GB.
Before the work, a report of orders by country showed 41 rows, and Ireland's real share was split across 24 of them. After the work it shows five rows and one honest line for unknowns.
Here is the seed, the model and the tests. The seed:
spelling_key,iso2
ireland,IE
republic of ireland,IE
rep. of ireland,IE
roi,IE
irl,IE
ie,IE
co. clare,IE
co. kerry,IE
united kingdom,GB
uk,GB
gb,GB
northern ireland,GB
france,FR
deutschland,DE
germany,DE
netherlands,NL
holland,NL
The staging model, in BigQuery SQL:
-- models/staging/legacy/stg_legacy__addresses.sql (BigQuery)
with source as (
select * from {{ source('legacy', 'addresses') }}
),
keyed as (
select
address_id,
country_text as country_raw,
-- match key: NFKC (turns a no break space into a space), case folded,
-- invisible characters removed, spaces collapsed, trimmed
trim(regexp_replace(
regexp_replace(normalize_and_casefold(country_text, NFKC), r'[\x{200B}\x{FEFF}\x{00AD}]', ''),
r'\s+', ' '
)) as country_key,
zipcode as postcode_raw,
upper(regexp_replace(zipcode, r'\s', '')) as postcode_compact
from source
)
select
k.address_id,
k.country_raw,
case
when m.iso2 = 'IE' and starts_with(k.postcode_compact, 'BT') then 'GB'
else m.iso2
end as country_iso2,
case
when m.iso2 is null then 'unmapped'
when m.iso2 = 'IE' and starts_with(k.postcode_compact, 'BT') then 'corrected_by_postcode'
else 'mapped'
end as country_status,
k.postcode_raw
from keyed as k
left join {{ ref('country_spellings') }} as m
on k.country_key = m.spelling_key
The left join matters: an inner join would silently drop every unmapped address, and the quarantine would be empty for the wrong reason. The tests, in the model's YAML file, check the seed and the output. The arguments key is the current dbt syntax, and older versions put values directly under the test name10. Here they are:
# models/staging/legacy/_legacy__models.yml
version: 2
seeds:
- name: country_spellings
columns:
- name: spelling_key
data_tests: [unique, not_null]
models:
- name: stg_legacy__addresses
columns:
- name: country_iso2
data_tests:
- accepted_values:
arguments:
values: ['IE', 'GB', 'FR', 'DE', 'NL']
- name: country_status
data_tests:
- accepted_values:
arguments:
values: ['mapped', 'corrected_by_postcode', 'unmapped']
And a singular test that turns the quarantine into a signal: it warns when any address is unmapped, and fails the run when more than 50 are, because that means something upstream changed:
-- tests/legacy_addresses_unmapped_countries.sql
{{ config(severity = 'error', warn_if = '>0', error_if = '>50') }}
select address_id, country_raw
from {{ ref('stg_legacy__addresses') }}
where country_status = 'unmapped'
The warn_if and error_if thresholds are standard dbt test configuration11.
The same pattern fixes the 3PL's SKUs. The shop's SKU for a 350 ml oat mug is MUG-OAT-350. The 3PL writes WRN_MUG_OAT_350, sometimes in lower case: its own prefix, underscores instead of hyphens. If the difference is a pure, reversible pattern, a function does the job (drop the WRN_ prefix, swap underscores for hyphens, upper case) and a relationship test checks that every result exists in spree_variants.sku. The moment the 3PL renames a single product by hand, the pattern is no longer pure, and a mapping table replaces the function. A function that works for 99% of rows and quietly mangles the rest is worse than a table that is honest about all of them.
Dates: parse with an explicit format, never let a tool guess
"03/04/2026" is the 3rd of April in Limerick and the 4th of March in a file exported by a tool set to American English. Neither reading is wrong. Guessing between them is. Many libraries will happily guess, and some guess per row, so a single column can end up with both interpretations: every date up to the 12th of the month read one way and every later date read the other, because "13/04" cannot be a month.
The rule:
- Every source gets its own explicit format string, chosen from the source's documentation or confirmed by looking at days above 12.
- Parsing a whole column with that format must fail loudly on any row that does not match, never fall back to guessing.
- Every date leaves staging in ISO 8601 form (
2026-04-03), as a realDATEtype, never as text.
Spreadsheets add one more format: the serial number. Excel stores a date as a count of days. Because of a decision copied from Lotus 1 2 3 decades ago, Excel treats 1900 as a leap year, so it counts a 29 February 1900 that never existed12. In practice, a serial number for any date after February 1900 converts correctly if you count from 30 December 1899. When a hand kept spreadsheet is exported as CSV and a date cell loses its formatting, the CSV contains "46027" instead of a date.
Example: three sources, three formats
Callum documents the date format of every source Shannonside Home loads:
| Source | Raw example | Format | Parsed |
|---|---|---|---|
| 3PL returns CSV | 05/01/2026 14:20 | %d/%m/%Y %H:%M, local time | 5 January 2026, 2.20pm in Limerick |
| Supplier XML feed | 2026-01-05T14:20:00Z | ISO 8601 with Z for UTC | 5 January 2026, 2.20pm UTC |
| Niamh's marketing costs sheet | 46027 | Excel serial number | 5 January 2026 |
The serial number works out like this. Counting 46,027 days from 30 December 1899 lands on 5 January 2026. In Python, date(1899, 12, 30) + timedelta(days=46027) gives 2026-01-05. In BigQuery, date_add(date '1899-12-30', interval 46027 day) gives the same.
For the 3PL file, Callum uses BigQuery's PARSE_TIMESTAMP, which takes the format first and the string second13, with the SAFE. prefix so a row that does not match returns NULL instead of stopping the whole query14. The NULL is not hidden: a status column turns it into a quarantined row.
-- BigQuery: parse the 3PL's local time stamps with an explicit format
select
return_id,
scanned_at_raw,
safe.parse_datetime('%d/%m/%Y %H:%M', scanned_at_raw) as scanned_at_local,
if(safe.parse_datetime('%d/%m/%Y %H:%M', scanned_at_raw) is null,
'unparseable', 'ok') as scanned_at_status
from {{ source('threepl', 'returns') }}
Notice that this parses into a DATETIME, a date and time with no time zone. That is deliberate. The 3PL's values are local wall clock times, and turning them into real moments needs the next section.
Time zones: a local time without a zone is half a fact
A time stamp means nothing until you know its zone. "25 October 2026, 1.30am" is a wall clock reading. To compare it with an order placed on the website, you need the moment it refers to, which means converting it to UTC (Coordinated Universal Time, the time zone with no offset and no daylight saving).
Shannonside Home has three kinds of time stamp:
- The shop stores UTC, as Rails does by default.
- GA4's daily BigQuery export has both.
event_timestampis in microseconds and UTC, whileevent_dateis a date string in the time zone set on the GA4 property15. Mixing the two in one query moves events across midnight. - The 3PL writes local time in Limerick, with no zone and no offset.
Converting local time to UTC is simple on 363 days of the year. In winter, Irish time equals UTC. In summer it is one hour ahead. On the other two days it is not simple at all. Ireland changes its clocks with the rest of the EU, at 1am UTC on the last Sunday of March and the last Sunday of October16. In 2026 that is 29 March and 25 October.
- On 29 March 2026, the local times from 1am to 2am never happen. A time stamp of 1.30am that day is impossible.
- On 25 October 2026, the local times from 1am to 2am happen twice: once in summer time, and an hour later again in winter time. A time stamp of 1.30am that day is ambiguous.
Here is the expert trap: different tools resolve the ambiguity differently, and neither tells you it did so. Python's zoneinfo uses the attribute fold from PEP 495. With the default fold=0, it takes the offset from before the transition, so 1.30am becomes the first occurrence, in summer time17. PostgreSQL documents the opposite choice: an ambiguous time is given the offset that applies after the transition, which in most zones means "standard time is preferred when in doubt"18. The same raw value, converted by a Python loader and by a PostgreSQL query, ends up one hour apart.
Ireland adds a twist of its own. Under the Standard Time (Amendment) Act 1971, Irish standard time is the summer time, one hour ahead of Greenwich, and Greenwich time in winter is legally the exception19. The IANA time zone database models this faithfully, as a negative daylight saving time in winter, and its maintainers record that in January 2018 these negative values broke tests in two widely used libraries, ICU and OpenJDK16. So "standard time" means something different in Dublin than in London. Reason in offsets from UTC, never in the words "standard" and "summer".
The rules for times:
- Store moments in UTC. Convert to local time only for display and for deciding which day a sale belongs to (a later chapter in this series covers that day boundary as a business rule).
- Use zone names from the IANA time zone database, such as
Europe/Dublin, never fixed abbreviations like "IST" or "GMT", which do not change with the season16. - Detect ambiguous and impossible local times and flag them. Do not let a library choose silently.
- Best of all, fix it at the source: ask the 3PL to send an offset (
2026-10-25T01:30:00+01:00) or UTC. Until it does, the flag stays.
Example: the night shift on 25 October
The 3PL runs a night shift that scans returns. In the file for 25 October 2026, 14 rows carry times between 1am and 2am local time. Take the row 25/10/2026 01:30.
- If it was the first 1.30am (still summer time, UTC plus one hour), the moment is 00:30 UTC.
- If it was the second 1.30am (winter time, UTC), the moment is 01:30 UTC.
Callum tests both tools on that value. Python with zoneinfo and the default fold gives 00:30 UTC. PostgreSQL, asked for '2026-10-25 01:30'::timestamp at time zone 'Europe/Dublin', gives 01:30 UTC. One hour apart, both without a warning.
Does an hour matter? For the 14 rows it decides whether a return was scanned before or after the shift's 1am break, which is how the 3PL's productivity report counts them, and it decides the order of events when Callum computes how long a refund took from the moment the parcel was scanned. More importantly, it is an hour of silent disagreement between two parts of the same pipeline, and that kind of disagreement erodes trust in every number built on top.
So Callum's loader flags these rows instead of picking:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo
def local_to_utc(value, fmt, zone):
"""Parse a local time stamp with an explicit format and zone.
Returns (utc datetime, status). Status is 'ambiguous' in the repeated
hour in autumn and 'nonexistent' in the skipped hour in spring.
"""
naive = datetime.strptime(value, fmt) # raises ValueError if fmt does not match
tz = ZoneInfo(zone)
first = naive.replace(tzinfo=tz, fold=0)
second = naive.replace(tzinfo=tz, fold=1)
if first.utcoffset() != second.utcoffset():
# Either the hour happened twice, or it never happened at all.
round_trip = first.astimezone(timezone.utc).astimezone(tz).replace(tzinfo=None)
status = "ambiguous" if round_trip == naive else "nonexistent"
return first.astimezone(timezone.utc), status
return first.astimezone(timezone.utc), "ok"
print(local_to_utc("25/10/2026 01:30", "%d/%m/%Y %H:%M", "Europe/Dublin"))
# (datetime(2026, 10, 25, 0, 30, tzinfo=timezone.utc), 'ambiguous')
print(local_to_utc("29/03/2026 01:30", "%d/%m/%Y %H:%M", "Europe/Dublin"))
# (datetime(2026, 3, 29, 1, 30, tzinfo=timezone.utc), 'nonexistent')
The function still returns a moment, so nothing downstream breaks, but the status column says the moment is a convention, not a fact. Fourteen rows a year carry the flag. Niamh's email to the 3PL asking for an offset in the file costs nothing.
Eircodes and postal codes: each market has its own shape
An Eircode or a postal code looks like a simple text field, and each country gives it a different structure. Standardising one means two separate steps: putting it in its canonical shape (case, spacing), and checking whether that shape is possible for the country. Whether the code actually exists, and belongs to that house, is a third question that only a lookup against the official address data can answer. Do not confuse them.
| Market | Structure | Canonical form | Source |
|---|---|---|---|
| Ireland | Eircode: seven characters, a three character routing key and a four character unique identifier, one per address | A65 F4E2 | Eircode20 |
| United Kingdom, including Northern Ireland | An outward code of 2 to 4 characters, a space, then an inward code of a digit and two letters, upper case | BT1 5GS | GOV.UK and ONS2122 |
| Germany | Five digits, nationwide since 1 July 1993 | 01067 | Bundesarchiv23 |
| Austria | Four digits, the official list published by the regulator RTR | 6020 | RTR24 |
Two traps sit in that table. First, German postal codes can start with a zero (Dresden is 01067). Store one as a number and it becomes 1067, which is wrong and looks almost right. These codes are text, always. Second, the shape check is per country, so the country must be standardised first. A five digit code is fine in Germany and nonsense in Ireland.
An Irish shop has one more trap of its own: history. Eircodes were assigned to every address in 2015, and a customer who last ordered before then, or who simply left the field empty, has no Eircode on file. That is a missing value with a perfectly good reason, not an error, and it gets its own status.
Example: tidying the Eircodes in the old addresses
Of the 19,824 legacy addresses in IE, Callum finds Eircodes typed in every way: v94t9px, V94T9PX, V94 T9PX, v94 T9px. The rule: remove all whitespace, upper case, check the shape, then put exactly one space after the three character routing key.
import re
EIRCODE_SHAPE = re.compile(r"^[A-Z][0-9][0-9W][0-9A-Z]{4}$")
def standardise_eircode(value):
"""'v94t9px ' becomes 'V94 T9PX'. Returns None when the shape is wrong."""
if value is None:
return None
compact = re.sub(r"\s", "", value).upper()
if not EIRCODE_SHAPE.match(compact):
return None
return f"{compact[:3]} {compact[3:]}"
The pattern is a shape check only (the W allows for the Dublin 6W routing key), not proof that the Eircode exists. Run over the 19,824 addresses, 14,210 were already in the canonical form, 3,302 are reshaped, 2,270 have no Eircode at all and get the status "missing", and 42 fail the shape check, mostly a letter O typed for a zero. Those 42 go to quarantine. The reshaped 3,302 change nothing a postman would notice, but they now match the routing key lookup Niamh's courier uses to price deliveries to the islands and remote areas, which had been charging the default rate for them.
Phone numbers: E.164, and why "valid" does not mean "theirs"
Phone numbers arrive as "061 234 567", "+353 (0)61 234 567", "00353 61 234 567", "61 234 567" and many more. The standard form is E.164, the International Telecommunication Union's numbering plan25. It is a plus sign, the country code and the national number, with no spaces or punctuation, so +35361234567. (The Irish numbers in this section are invented.)
Do not write the parser yourself. Google's libphonenumber holds the numbering rules for every country and is updated as they change. Its Python port is called phonenumbers26. Three functions do most of the work: parse (which needs a default region for numbers written without a country code), is_valid_number, and format_number with PhoneNumberFormat.E164. A number that cannot be parsed raises NumberParseException.
Two traps.
The default region comes from the address, not from the shop. "028 9649 6123" is a Belfast number. Parsed with the default region IE, libphonenumber reads it as an Irish number and calls it invalid. Parsed with GB, it is valid: +442896496123. A shop in Limerick that delivers north of the border must use the delivery country as the default region.
Valid means "possible in an allocated range", not "belongs to this person". Ofcom, the UK regulator, reserves ranges for television and radio drama that will never be given to a real customer, such as 028 9649 6000 to 6999 for Belfast and 07700 900000 to 900999 for UK mobiles27. The Belfast range passes libphonenumber's check, which is exactly why this article uses it. The mobile range does not: phonenumbers.is_valid_number returns False for 07700 900123, because libphonenumber knows that block is not in service. Neither result tells you whether a customer will answer. Only sending a code to the number does that.
Example: a month of phone numbers
In one month, Shannonside Home takes 1,980 orders. Callum standardises the delivery phone number on each, using the delivery country as the default region:
import phonenumbers
def standardise_phone(value, default_region):
"""Return (E.164 string or None, status)."""
text = (value or "").strip()
if not text:
return None, "missing"
try:
number = phonenumbers.parse(text, default_region)
except phonenumbers.NumberParseException:
return None, "unparseable"
if not phonenumbers.is_valid_number(number):
return None, "invalid"
return phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164), "ok"
print(standardise_phone("+353 (0)61 234 567", "IE")) # ('+35361234567', 'ok')
print(standardise_phone("028 9649 6123", "IE")) # (None, 'invalid')
print(standardise_phone("028 9649 6123", "GB")) # ('+442896496123', 'ok')
The result for the month:
1,940 numbers are valid. They arrived in four different formats and now share one. 40 are not: 22 missing, 11 invalid and 7 unparseable. As a share of the month:
That is of the month's orders, and it matches what profiling found. The fix for the 40 belongs at the source: the checkout form now uses the same library to check the number as the customer types it, with a friendly message. The pipeline keeps flagging, because old orders and the 3PL's data will never pass through that form.
Units: a number without its unit is a guess
A product is "45" high. Centimetres or millimetres? Solidus stores height, width, depth and weight on each variant as plain decimal numbers, with no unit column8. The unit is a convention of the shop, which means it must be written down, and every source that feeds those columns must be converted to it.
The rule:
- In staging, keep the value and the unit as two columns, taken from the source's documentation, never inferred from the size of the number.
- Convert to one canonical unit with a small conversion table. Millimetres as whole numbers is a good canonical unit for lengths, because it needs no decimals. Grams do the same job for weight.
- Add a plausibility check per product type, which catches the conversion that was forgotten.
Example: the floor lamp that was 14.5 metres tall
Shannonside Home gets product data from several supplier feeds. One lighting supplier sends dimensions in millimetres, the others send centimetres. The shop's convention, written in Callum's rule register, is centimetres in Solidus. When the lighting supplier's feed was first loaded, nobody converted it. A floor lamp 1,450 mm tall went into Solidus as 1,450, which the shop reads as 1,450 cm: 14.5 metres.
Nobody noticed on the product page, because the shop shows dimensions from a text description. The courier integration noticed for them: it used the dimensions to choose a parcel size and charged the lamp as a two person delivery, at a loss on every order.
Callum's fix has three parts. The staging model for supplier feeds now carries a length_unit column set per supplier. A conversion function turns every length into millimetres:
from decimal import Decimal
TO_MM = {"mm": Decimal("1"), "cm": Decimal("10"), "m": Decimal("1000")}
def length_in_mm(value, unit):
"""Convert a length to millimetres. Unknown units raise, they never guess."""
return (Decimal(str(value)) * TO_MM[unit.strip().lower()]).quantize(Decimal("1"))
length_in_mm("1450", "mm") # Decimal('1450')
length_in_mm("45", "cm") # Decimal('450')
And a plausibility rule flags any homeware product taller than 3 metres. Run on all 1,400 products, it flags 64, every one of them from the lighting supplier. The lamp is now 1,450 mm in the warehouse and 145 cm in Solidus, and the courier charges a normal parcel rate.
Money: exact amounts, never floating point
Money must be stored as an exact decimal amount. Floating point numbers (float in Python, double precision in PostgreSQL, FLOAT64 in BigQuery) store most decimal fractions approximately, which is fine for physics and wrong for a ledger. The classic illustration: in Python, 0.1 + 0.2 prints 0.30000000000000004.
Shannonside Home's legacy import from the old platform stored prices as floats. That is why the raw table contains values such as 19.990000000000002. Solidus itself stores amounts as decimal with two decimal places8, so the shop's own data is exact. Only the imported history needs repair.
Two details decide whether the repair is right.
Convert from the shortest representation, not from the binary value. Python's Decimal(2.675) gives the exact binary value, 2.67499999999999982236431605997495353221893310546875, which rounds down. Decimal(repr(2.675)) gives 2.675, the number the old system meant to store. For a float that came from a two decimal price, the shortest representation is the intended value.
Choose the rounding rule on purpose. Python's built in round() rounds halves to the even neighbour, and on floats it gives surprises: its documentation notes that round(2.675, 2) gives 2.67, because the float is slightly below 2.67528. PostgreSQL's round() on numeric breaks ties away from zero, while on double precision the tie breaking depends on the platform29. Finance usually expects half up, away from zero. Write the rule down and use Decimal with an explicit rounding mode, so the answer does not depend on which tool ran.
Example: repairing a float price
from decimal import Decimal, ROUND_HALF_UP
def money_from_float(value):
"""Legacy float price to an exact amount in euro, half up to the cent."""
return Decimal(repr(value)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
money_from_float(19.990000000000002) # Decimal('19.99')
money_from_float(2.675) # Decimal('2.68')
Across five years of legacy order lines, 18,214 prices carry float noise. After repair, the sum of the legacy order totals differs from the old platform's own monthly revenue reports by exactly €0.00 in 57 months and by one cent in 3. Callum records those three cents, with the reason (the old platform rounded per order, the repair rounds per line), in the rule register. Three explained cents are better than a reconciliation that "nearly" works.
Currencies: store the amount and the currency, and never add across them
Shannonside Home sells mostly in euro, and since it opened a sterling price list for customers in Northern Ireland, some orders are in pounds. Solidus stores the currency on each order in spree_orders.currency and on each price in spree_prices.currency8. That is the first rule: an amount without its currency is not an amount. The currency is part of the value, as the unit is part of a length.
The second rule: never sum across currencies. A column called total that holds 84 for one order and 80 for the next is not a list of numbers you can add up if one is euro and the other pounds.
The third rule: convert with a dated rate, and record which rate. For reporting, a common choice is the European Central Bank's euro foreign exchange reference rates. The ECB publishes them on working days at around 4pm Central European Time, for about 30 currencies against the euro, and states that they are published for information purposes only30. That makes them a good, citable basis for management reporting, and not a substitute for the rates your payment provider actually applied, which belong to finance and reconciliation. On days with no reference rate (weekends and holidays), use the last rate published before the order date, and write that rule down too.
The conversion, for a rate quoted as pounds per euro:
where is the amount in pounds, is the ECB reference rate on day in pounds per euro, and is the amount in euro. Converting with a rate is a ratio applied to an amount, and Foundations: ratios and rates explains the idea from scratch.
Example: November's revenue, added up wrongly and then rightly
On 23 November 2026 the ECB reference rate was 0.83673 pounds per euro30. An order from Newry on that day for £80.00 converts to:
so the order is worth euro, rounded to the cent.
Now a whole month, kept simple by assuming that day's rate for every sterling order (in the real model, each order uses its own day's rate). Shannonside Home takes 1,862 orders in euro, totalling €156,408.00, and 118 orders in pounds, totalling £9,440.00.
The naive query adds the total column and reports €165,848.00. That treats every pound as a euro.
The correct query converts the sterling orders first:
that is euro, and adds them to the euro orders: €156,408.00 plus €11,282.01 is €167,690.01.
The naive figure understates revenue by €1,842.01, which is 1.10%. Small enough to survive a glance, large enough to change a decision about the Northern Ireland price list. And the direction depends on the rate: a currency worth less than the euro would make the same query overstate revenue instead.
In the warehouse, Callum keeps the rates as a table loaded daily from the ECB, and converts in one model:
-- models/intermediate/int_orders__in_eur.sql (BigQuery)
select
o.order_id,
o.currency,
o.total as total_original,
r.rate_date,
case
when o.currency = 'EUR' then o.total
when o.currency = 'GBP' then round(o.total / r.gbp_per_eur, 2)
end as total_eur
from {{ ref('stg_shop__orders') }} as o
left join {{ ref('int_ecb_rates__filled') }} as r
-- each calendar day carries the last published rate on or before it
on r.calendar_date = date(o.completed_at, 'Europe/Dublin')
A not_null test on total_eur catches any new currency the model has not been told about. Better to fail than to quietly drop orders in Swiss francs the day someone opens a new price list.
VAT: decide whether a number includes it, and say so
The last money trap is tax. Shannonside Home's prices include Irish VAT at the standard rate of 23%31. An order total of €84 includes €15.71 of VAT. Some reports need revenue with VAT (what the customer paid), some without (what the business keeps), and a column that silently mixes the two makes every margin wrong.
Solidus keeps the two kinds of tax apart on each order: included_tax_total for tax already inside the prices, as in Ireland, and additional_tax_total for tax added on top, as in markets that quote prices before tax8. A standardised order model carries both a gross and a net amount, named so nobody can confuse them.
To take VAT out of an amount that includes it:
where is the gross amount including VAT, is the VAT rate as a decimal (0.23 for 23%), and is the net amount. Percentages as decimals are covered in Foundations: percentages.
Example: the €84 order, and the cent that moves
For the average order:
so : €68.29 net and €15.71 VAT.
Now five tea lights at €1.99 each, €9.95 in total. Compute the net amount per unit and multiply: €1.99 divided by 1.23 is €1.6179, rounded to €1.62, times five is €8.10. Compute it on the line total instead:
So on the line against per unit: one cent apart, and both methods are defensible. What is not defensible is using one method in the shop's VAT report and the other in the data warehouse, then spending a morning finding the cent. Callum's standard follows the shop: Solidus has already calculated the tax per order, so the warehouse takes included_tax_total as given and never recalculates it. Net revenue is the total minus the included tax. The purchase event chapter covers the same decision for analytics, and the unit economics chapter shows why margins must be built on net amounts.
Yes, Y, 1, TRUE and the empty cell
Yes or no flags look like the easiest standardising job, and they hide the most consequential mistake in the chapter. A newsletter opt in, a gift flag, a "business customer" tick box: each arrives as "Yes", "Y", "y", "1", "TRUE", "x", or an empty cell, depending on the tool that exported it.
PostgreSQL's own boolean type shows how generous a parser can be: it accepts true, yes, on and 1 for true, false, no, off and 0 for false, ignores case and surrounding spaces, and accepts unique prefixes such as y and n32. It rejects anything else, which is the right instinct: a value you do not recognise is an error, not a no.
The rule:
- Map every recognised spelling to true or false with an explicit list.
- Map an empty cell, and anything unrecognised, to unknown (
NULL), never to false. - Where the flag records a permission, such as marketing consent, unknown is never treated as yes. The tool that recorded the consent is the source of truth, and the warehouse only reflects it.
Example: 38,000 subscribers and five spellings
The newsletter tool's export has a column marketing_opt_in. Five years of imports and tool changes left these values across the 38,000 rows:
| Raw value | Rows | Standard value |
|---|---|---|
Yes | 31,250 | true |
Y (old import) | 2,100 | true |
1 (old platform) | 1,890 | true |
No | 1,400 | false |
| empty | 1,360 | unknown |
A report that counts marketing_opt_in = 'Yes' finds 31,250 subscribers who opted in. The true figure is 35,240: the query missed 3,990 people, 10.5% of the list, because their "yes" was spelled differently. A report that treats the empty cell as "no" would count 2,760 refusals instead of 1,400, nearly double. And a report that treats the empty cell as "yes", because "they are on the newsletter list after all", would claim consent nobody can show. Callum's model maps the 1,360 to NULL and Niamh checks them against the newsletter tool's own consent records, which is where the answer actually lives.
TRUE_WORDS = {"y", "yes", "true", "t", "1", "x"}
FALSE_WORDS = {"n", "no", "false", "f", "0"}
def parse_flag(value):
"""True, False or None. An empty or unknown value is None, never False."""
key = (value or "").strip().casefold()
if key in TRUE_WORDS:
return True
if key in FALSE_WORDS:
return False
return None
Putting it together: one standardisation step with a quarantine
Every technique in this chapter has the same shape. A raw value arrives. It is kept. It is cleaned as text. A rule or a mapping turns it into a standard value. A check confirms the result is possible. If anything fails, the standard value stays empty, the status says why, and the row waits in quarantine for a person or a better rule.
Because standardising is a set of small, pure functions, it is the easiest part of a pipeline to test, and the part where tests pay back fastest. I work test first on every project, and here it means writing the awkward cases down before writing the function: the trailing space, the decomposed "ë", the ambiguous hour, the euro order. If test first is new to you, test driven development explained covers the habit, and what to test where covers the layers. A later chapter in this series goes deep on testing data pipelines. Here are the two kinds of test that matter most for standardising.
Example: Callum's tests, in Python and in dbt
The Python functions from this chapter live in one module, standardise.py, with one test file. A few of the tests, written with pytest:
# tests/test_standardise.py
from datetime import datetime, timezone
from decimal import Decimal
import pytest
from standardise import (clean_text, match_key, standardise_phone,
local_to_utc, money_from_float, parse_flag)
def test_clean_text_removes_invisible_and_extra_spaces():
assert clean_text(" Niamh\u00a0 Walsh\u200b ") == "Niamh Walsh"
def test_clean_text_composes_the_fada():
assert clean_text("Sea\u0301n") == "Se\u00e1n"
def test_match_key_folds_case_and_sharp_s():
assert match_key("STRASSE") == match_key("Straße") == "strasse"
def test_belfast_number_needs_the_uk_region():
assert standardise_phone("028 9649 6123", "IE") == (None, "invalid")
assert standardise_phone("028 9649 6123", "GB") == ("+442896496123", "ok")
def test_ambiguous_hour_is_flagged_not_guessed():
utc, status = local_to_utc("25/10/2026 01:30", "%d/%m/%Y %H:%M", "Europe/Dublin")
assert status == "ambiguous"
assert utc == datetime(2026, 10, 25, 0, 30, tzinfo=timezone.utc)
def test_float_prices_become_exact():
assert money_from_float(19.990000000000002) == Decimal("19.99")
@pytest.mark.parametrize("raw,expected", [("Y", True), ("1", True), ("No", False),
("", None), ("maybe", None)])
def test_flags_never_turn_unknown_into_false(raw, expected):
assert parse_flag(raw) is expected
In the module, clean_text normalises to NFC, removes the invisible characters, collapses whitespace and trims, and match_key applies casefold() to the result. The full file holds 30 tests, and all of them pass.
For the SQL side, dbt unit tests (available since dbt 1.8) check a model's logic against a few hand written input rows, without touching real data33. This one pins down the BT rule:
# models/staging/legacy/_legacy__unit_tests.yml
unit_tests:
- name: ireland_with_a_bt_postcode_is_gb
model: stg_legacy__addresses
given:
- input: source('legacy', 'addresses')
rows:
- {address_id: 1, country_text: "Ireland", zipcode: "bt35 6aa"}
- {address_id: 2, country_text: "Ireland", zipcode: "V94 T9PX"}
- {address_id: 3, country_text: "Atlantis", zipcode: "A65 F4E2"}
- input: ref('country_spellings')
rows:
- {spelling_key: "ireland", iso2: "IE"}
expect:
rows:
- {address_id: 1, country_iso2: "GB", country_status: "corrected_by_postcode"}
- {address_id: 2, country_iso2: "IE", country_status: "mapped"}
- {address_id: 3, country_iso2: null, country_status: "unmapped"}
One night's run of the whole standardisation layer at Shannonside Home now ends with a short summary that Callum reads with his coffee: rows in, rows standardised, rows quarantined per column and per reason. On a normal night the quarantine holds a few dozen rows. On the night a supplier changes its feed, it holds a few hundred, and the run stops before a single wrong number reaches Niamh's dashboard.
Standardising must never make the data less accurate
There is a legal side to this, and it points the same way as good engineering. Under the GDPR, personal data must be accurate and, where necessary, kept up to date, and every reasonable step must be taken to erase or rectify inaccurate data without delay. That is the accuracy principle in Article 5(1)(d)34. The Data Protection Commission puts it the same way in its guidance on the principles, and adds that controllers should keep a record of where the data came from35.
The fada has been tested against exactly this principle. In a 2019 note on rectification complaints, the DPC looked at names recorded without their diacritical marks. It did not set a fixed rule. It asks whether the purpose of the processing is still achieved without the fada, whether the name is used on its own or alongside other identifiers, and it treats each complaint on its own merits, noting that the right to rectification is not absolute36. For a data engineer the lesson is simpler than the law: if your systems can store the fada, there is no reason to drop it, and every reason to keep it.
For standardising, that means:
- Standardise the form, never the facts. Turning "v94t9px" into "V94 T9PX" is fine. Turning "Siobhán" into "Siobhan" for storage changes a person's name, and the person may rightly object.
- Keep display values and match keys apart. Fada free, case folded keys are a tool for finding matches. They never replace the stored name.
- A guessed value is an inaccurate value. Filling an unknown country with "Ireland", or an unknown consent with "yes", creates personal data that is wrong, which is exactly what the accuracy principle forbids.
- Corrections flow back. When the quarantine reveals a wrong address, the fix belongs in the shop, where the customer's record lives, not only in the warehouse.
This is general information about the law, not legal advice. If your case is unusual, ask a solicitor who knows data protection.
Example: the name that came back from the 3PL
The 3PL's systems cannot store the fada, so their return file lists a customer as "Siobhan Delaney". When Callum's pipeline joins returns to customers, the match key (case folded, accents stripped for comparison) finds "Siobhán Delaney" in the shop. The return is linked to the right customer. The shop's record still says "Siobhán". Nothing from the 3PL's spelling flows back into the customer table, because the shop's record is the accurate one and the 3PL's is a lossy copy. The standardisation did its job: it made two forms comparable without making either one less true.
Conclusion
Standardising is how the same thing comes to look the same everywhere. Keep the raw value, write the standard value beside it, and record how it got there. Normalise text to NFC, remove the characters nobody can see, and compare with folded match keys while storing what the customer typed. Declare every file's encoding. Map categories through a version controlled table, with ISO codes (IE for Ireland, GB for the whole United Kingdom, Northern Ireland included) and a quarantine for anything new. Parse dates with explicit formats, store moments in UTC, and flag the hour that happens twice instead of letting a tool choose. Treat Eircodes and postal codes as text with a shape per country, phone numbers as E.164 with the delivery country as the default region, and lengths as a value plus a unit. Store money as exact decimals with its currency, convert with a dated rate, never add across currencies, and say whether a number includes VAT. Map yes and no explicitly, and let unknown stay unknown. Then test every rule, because these small functions decide whether every report built on them can be trusted.
