DEV Community

Tyler Dockswell
Tyler Dockswell

Posted on

Decode a METAR in 30 lines of Python (and the one rule the FAA Part 107 test loves)

A METAR is an airport weather report in one dense line of text. If you fly drones commercially in the US, you have to read them for the FAA Part 107 knowledge test. If you write code, they're also a nice little parsing exercise: fixed tokens, a few regexes, one gotcha.

Here's one (a made-up example in the real format):

KMLB 141753Z 09012G18KT 10SM FEW025 SCT040 BKN250 27/19 A3012
Enter fullscreen mode Exit fullscreen mode

Read it left to right:

Token Meaning
KMLB Station (Melbourne, FL)
141753Z Day 14, 17:53 UTC (Zulu)
09012G18KT Wind from 090° at 12 knots, gusting 18
10SM Visibility 10 statute miles
FEW025 SCT040 BKN250 Cloud layers at 2,500 / 4,000 / 25,000 ft AGL
27/19 Temp 27 °C, dewpoint 19 °C (M prefix = minus)
A3012 Altimeter 30.12 inHg

The decoder

import re

def decode_metar(metar: str) -> dict:
    out = {"clouds": []}
    for tok in metar.split():
        if re.fullmatch(r"[A-Z]{4}", tok) and "station" not in out:
            out["station"] = tok
        elif m := re.fullmatch(r"(\d{2})(\d{2})(\d{2})Z", tok):
            out["time"] = f"day {m[1]}, {m[2]}:{m[3]} UTC"
        elif m := re.fullmatch(r"(\d{3}|VRB)(\d{2,3})(?:G(\d{2,3}))?KT", tok):
            wind = f"{m[1]}° at {int(m[2])} kt" if m[1] != "VRB" else f"variable at {int(m[2])} kt"
            out["wind"] = wind + (f", gusting {int(m[3])} kt" if m[3] else "")
        elif m := re.fullmatch(r"(\d+(?:/\d+)?)SM", tok):
            out["visibility_sm"] = m[1]
        elif m := re.fullmatch(r"(FEW|SCT|BKN|OVC)(\d{3})", tok):
            out["clouds"].append((m[1], int(m[2]) * 100))
        elif m := re.fullmatch(r"(M?\d{2})/(M?\d{2})", tok):
            c = lambda s: -int(s[1:]) if s.startswith("M") else int(s)
            out["temp_c"], out["dewpoint_c"] = c(m[1]), c(m[2])
        elif m := re.fullmatch(r"A(\d{4})", tok):
            out["altimeter_inhg"] = int(m[1]) / 100
    # Ceiling = lowest BKN or OVC layer (FEW and SCT never count)
    layers = [ft for cov, ft in out["clouds"] if cov in ("BKN", "OVC")]
    out["ceiling_ft_agl"] = min(layers) if layers else None
    return out

print(decode_metar("KMLB 141753Z 09012G18KT 10SM FEW025 SCT040 BKN250 27/19 A3012"))
Enter fullscreen mode Exit fullscreen mode

Output:

{'clouds': [('FEW', 2500), ('SCT', 4000), ('BKN', 25000)], 'station': 'KMLB',
 'time': 'day 14, 17:53 UTC', 'wind': '090° at 12 kt, gusting 18 kt',
 'visibility_sm': '10', 'temp_c': 27, 'dewpoint_c': 19,
 'altimeter_inhg': 30.12, 'ceiling_ft_agl': 25000}
Enter fullscreen mode Exit fullscreen mode

It skips plenty (remarks, weather codes like -RA, runway visual range, VV vertical visibility), but it covers what a beginner needs.

The gotcha: the ceiling

Look at the last few lines of the function. A ceiling is the lowest layer reported as broken (BKN) or overcast (OVC). FEW and SCT layers never count, however low they are.

So in the example above, the ceiling is 25,000 ft, not 2,500 ft. That's exactly the kind of question the Part 107 test likes to ask, because the low FEW025 layer is right there tempting you.

A naive min() over every cloud layer gets it wrong. So do a lot of people taking the test.

Two more test-relevant details the code makes obvious:

  • Cloud heights are in hundreds of feet AGL (025 = 2,500 ft).
  • Times are UTC, so convert before you decide whether the report is current.

Try it on live data

The free NOAA Aviation Weather Center API returns raw METARs:

https://aviationweather.gov/api/data/metar?ids=KMLB&format=raw
Enter fullscreen mode Exit fullscreen mode

Pipe that into decode_metar() and you have a tiny weather CLI.


Disclosure: I run Astra Pilot Academy, which sells independent Part 107 study aids. If you're studying for the test, there's a free 25-question PDF of commonly missed questions (astrapilot.gumroad.com/l/tmian) and a $5 METAR & TAF decoder drill (astrapilot.gumroad.com/l/metar-taf-decoder-drill). Not affiliated with or endorsed by the FAA. Always check official FAA sources.

Top comments (0)