BT San Technology

28 October 2026

Factory Charts with Mismatched Times: Checking Timestamps, Time Zones and Data Gaps

28 min read · Smart factory

Illustration: a data timeline screen with clocks and a factory gateway
AI-generated illustration

Two charts from the same machine. One says the machine stopped at 13:50. The other says it stopped at 13:52. Neither is lying. Each comes from a different clock, is written in a different format, and some are missing several minutes without telling anyone. Lay them on top of each other to find out what happened first, and the chart gives a confident wrong answer.

This article checks the time in factory data one layer at a time. It starts with reading the timestamp text correctly (UTC, offset, no offset, Buddhist Era years). Then it estimates how far a device clock has drifted, removes duplicate and out-of-order rows, and separates real machine-off periods from data gaps. Finally it shows how much each layer of error changes the downtime minutes per shift. All the code runs on Node 24 with nothing to install, and the output in the article is the output of a real run.

The real problem: one time value can mean several things

One row of factory data can carry at least three kinds of time: the time the event happened (event time), the time the central system received it (ingestion time), and the time the screen showed it (display time). If a device buffers data while the network is down and sends it all at once when the network returns, the ingestion time is minutes later than the event time. These three values should not be mixed in one column.

Problems also tend to come in stacks, each layer hiding behind the one before. The three hypothetical cases below do not come from any factory or customer. They are written to show common patterns.

  • Case 1: A factory exports gateway data in UTC, but the HMI screen at the machine logs local time with no offset. An engineer overlays the two files. A machine stop at 2 p.m. shows up at 7 a.m. on the other chart, and everyone thinks they are two separate events.
  • Case 2: One HMI has not synced its clock for months. It runs almost two minutes ahead of real time, and the gap keeps growing. Downtime minutes that fall across a shift boundary are counted for the wrong shift, so the efficiency reports for the two shifts do not match what the shift leads remember.
  • Case 3: During a short network drop, the gateway has no data for three minutes in the middle of a period when the machine is stopped. The report counts these three minutes as zero because there are no rows to count. The downtime figure ends up lower than the truth, even though nobody deleted anything.

All three cases are easy to fix if you know what to look for. The hard part is not fixing them silently. A value that was guessed or filled in without telling anyone becomes data that looks more trustworthy than the truth.

Facts from the documents this example is based on

TopicWhat the document saysEffect on our code
Timestamp format with offsetRFC 3339 defines the time-offset as Z or a numeric offset such as -08:00, and says -00:00 means the UTC time is known but the local offset is notparseTimestamp separates Z, numeric offset and no offset, and records a flag whenever it has to guess
NTP accuracyRFC 5905 (NTPv4) states that on a fast LAN with modern hardware, accuracy of tens of microseconds may be possible. This is an upper bound, not something every factory will getWe do not assume clocks are exactly right. We measure offset and drift from real event pairs
PTPIEEE 1588-2019 (Precision Time Protocol) is designed for measurement and control systems over a network, and the standard states sub-microsecond accuracy. chrony supports PTP as a reference clock and can use hardware timestamping on LinuxIf the job needs event order at millisecond level or finer, choose hardware and switches that support PTP. For downtime minutes per shift, NTP is enough
Time from OPC UAOPC UA Part 4 says sourceTimestamp must be UTC and should show when the value or statusCode last changedStore UTC in the storage layer and convert to local time only for display (store UTC, display local)
Buddhist Era yearsIn the Thai solar calendar, the Buddhist Era (B.E.) year is 543 years ahead of the Gregorian (C.E.) year, and the year has started on 1 January since B.E. 2484 (before that it started on 1 April)Years above 2400 have 543 subtracted and always get the be_year flag, because data from before B.E. 2484 is outside the scope of this example
Running the testsNode.js has a built-in test runner, started with node --testThe tests use node:test, so nothing extra needs installing
Summary of documents actually opened and read, as of the access date 2026-11-21. The source list is at the end of the article. The accuracy figures belong to the standard's authors or the software's developers. They were not measured in any factory.

Assumptions of the example: Asia/Bangkok is treated as UTC+7 all year with no daylight saving time (common knowledge; this example does not check it against a time zone database). Machine states are only RUN, STOP and OFF. All data files are made-up data, and the gateway that syncs with NTP is treated as the reference clock. If your factory's time zone, states or reference source differ from this, change the settings first.

Overview of the example and the files it produces

The simulated data covers one afternoon hour on 2 March 2026 (13:30 to 14:29 Thai time). One machine records its state every minute from three sources. The truth we set is that the machine is stopped (STOP) from 13:50 to 14:09, 20 minutes in total, split into 10 minutes in shift A and 10 minutes in shift B, and then switched off (OFF) from 14:20 to 14:24. The example has to recover this figure from data that is damaged in several ways.

FileRole
parse.tsConverts timestamp text to epoch UTC and flags whether the offset was guessed or a Buddhist Era year was converted
drift.tsEstimates a clock's offset and drift (ppm) from event pairs, then converts device time to reference time
ingest.tsReads the CSV and reports bad rows with their line numbers
series.tsSorts, removes duplicates, snaps rows to a 1-minute grid and finds gaps
align.tsLays the three sources on one grid, separates machine_off from no_data, and merges values with flags
kpi.tsCounts downtime minutes per shift: A 06-14, B 14-22, C 22-06
check.tsMain script. Prints the report and compares the KPI before and after the fixes
gen-data.tsCreates the files in data/. The result is the same every time
checks.test.tsTest suite with 8 cases using node:test
output.txtReal output of node check.ts

Each source is damaged differently, to show that no single method fixes every source. gateway.csv is UTC ending in Z, with a three-minute gap at 13:55, one duplicate row and one pair of out-of-order rows. historian.csv uses +07:00 but five rows have no offset. It has a three-minute gap at 14:12, a duplicate row whose values conflict, and one junk row, N/A. hmi.csv is local time with no offset, uses the Buddhist Era year 2569, and its clock has run about 25 ppm fast since 10 January. sync_pairs.csv holds six pairs of HMI time and reference time used to estimate the drift.

Step 1: Read the time correctly: UTC, offset, no offset and Buddhist Era years

This function takes the timestamp text and an assumed offset to use when the text does not give one (420 minutes is UTC+7). It returns UTC time in milliseconds, plus a flag every time it had to guess. Text that cannot be read, a year out of range, or a date that does not exist on the calendar, such as 31 February, makes it throw. It does not fix these on its own.

parse.ts · lines 7–43
// assumedOffsetMin ใช้เมื่อข้อความไม่มี offset (naive) เช่น 420 = UTC+7 (Asia/Bangkok ไม่มี DST)
export function parseTimestamp(raw: string, assumedOffsetMin: number): Parsed {
  const s = raw.trim();
  const flags: string[] = [];
  let y: number, mo: number, d: number, h: number, mi: number, sec: number;
  let msPart = 0;
  let offsetMin: number | null = null;

  const iso = ISO.exec(s);
  const dmy = DMY.exec(s);
  if (iso) {
    [y, mo, d, h, mi, sec] = iso.slice(1, 7).map(Number) as [number, number, number, number, number, number];
    if (iso[7]) msPart = Number(iso[7].padEnd(3, "0"));
    if (iso[8] === "Z") offsetMin = 0;
    else if (iso[8]) offsetMin = (iso[8][0] === "-" ? -1 : 1) * (Number(iso[8].slice(1, 3)) * 60 + Number(iso[8].slice(4, 6)));
  } else if (dmy) {
    // simplified: รูปแบบ วัน/เดือน/ปี เท่านั้น ของจริงต้องให้ config ระบุลำดับต่อแหล่งข้อมูล
    [d, mo, y, h, mi, sec] = dmy.slice(1, 7).map(Number) as [number, number, number, number, number, number];
  } else {
    throw new Error(`unrecognised timestamp: "${raw}"`);
  }

  if (y >= 2400) {
    y -= 543; // ปี พ.ศ. -> ค.ศ.
    flags.push("be_year");
  }
  if (y < 2000 || y > 2100) throw new Error(`year out of range: "${raw}"`);
  const utcLike = Date.UTC(y, mo - 1, d, h, mi, sec, msPart);
  const back = new Date(utcLike);
  if (back.getUTCDate() !== d || back.getUTCMonth() !== mo - 1) throw new Error(`invalid calendar date: "${raw}"`);

  if (offsetMin === null) {
    offsetMin = assumedOffsetMin;
    flags.push("naive_assumed_offset");
  }
  return { ms: utcLike - offsetMin * 60_000, flags };
}
parseTimestamp: the flags naive_assumed_offset and be_year show that the value was guessed

Note that the regex accepts the offset as optional. When there is no offset, the code does not stay silent. It adds a flag and uses the value the caller declared. This means every row whose zone was guessed can be counted later. The display function for the store UTC, display local rule is at the end of the same file.

parse.ts · lines 45–50
const pad = (n: number, w = 2) => String(n).padStart(w, "0");
// แสดงเป็นเวลาท้องถิ่น (UTC+7) เก็บใน UTC แสดงเป็นท้องถิ่น
export function fmtLocal(ms: number): string {
  const t = new Date(ms + 7 * 3600_000);
  return `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`;
}
Internal data is always UTC. It is converted to local time only when printing

simplified: The example supports only ISO format and day/month/year, and forces the +07:00 time zone for display. A real system should use a time library that knows the time zone database, and set the day/month order per source in a config.

Step 2: Estimate clock error from event pairs

A device clock that is not synced differs from real time in two ways: a fixed difference (offset) and a difference that grows over time (drift). The method in the example is to collect several time pairs (the time the device wrote, and the reference time at the same event), days apart, and then find the best-fit straight line by least squares. The slope is the drift in parts per million (ppm). 1 ppm is about 0.086 seconds per day.

drift.ts · lines 5–23
// offset(ref) = device - ref  ถูกประมาณเป็นเส้นตรง offsetMs + slope*(ref - t0) ด้วยกำลังสองน้อยสุด
export function fitClock(pairs: SyncPair[]): ClockFit {
  if (pairs.length < 2) throw new Error("need at least 2 pairs");
  const t0 = pairs[0].ref;
  const xs = pairs.map((p) => p.ref - t0);
  const ys = pairs.map((p) => p.device - p.ref);
  const n = pairs.length;
  const mx = xs.reduce((a, b) => a + b, 0) / n;
  const my = ys.reduce((a, b) => a + b, 0) / n;
  let sxy = 0, sxx = 0;
  for (let i = 0; i < n; i++) {
    sxy += (xs[i] - mx) * (ys[i] - my);
    sxx += (xs[i] - mx) ** 2;
  }
  const slope = sxy / sxx;
  const offsetMs = my - slope * mx;
  const residualMaxMs = Math.max(...xs.map((x, i) => Math.abs(ys[i] - (offsetMs + slope * x))));
  return { t0, offsetMs, driftPpm: slope * 1e6, residualMaxMs, n };
}
fitClock returns the offset, the drift and the maximum residual, so you know how well the line fits
drift.ts · lines 25–30
// แปลงเวลาที่อุปกรณ์เขียน -> เวลาอ้างอิง: device = ref + offset(ref) แก้หา ref
// simplified: เส้นตรงเส้นเดียว ของจริงอุณหภูมิทำให้ drift เปลี่ยนได้ ควร sync ซ้ำและตรวจ residual
export function toReference(fit: ClockFit, deviceMs: number): number {
  const slope = fit.driftPpm / 1e6;
  return (deviceMs - fit.offsetMs + slope * fit.t0) / (1 + slope);
}
toReference corrects the time the device wrote back to reference time

The maximum residual tells you how far to trust the straight line. If the residual is much larger than the resolution you need, temperature or something else is making the drift uneven. Sync more often instead of trying to correct after the fact.

Step 3: Read the file and set bad rows aside, not drop them silently

ingest.ts · lines 8–28
// simplified: split ด้วยเครื่องหมายจุลภาค ไม่รองรับ quoted field ของจริงใช้ตัวอ่าน CSV ที่เต็มรูปแบบ
export function ingest(text: string, cfg: SourceConfig): { rows: RawRow[]; bad: BadRow[] } {
  const lines = text.split(/\r?\n/).filter((l) => l.trim() !== "");
  const head = lines[0].split(",");
  const ti = head.indexOf(cfg.tsCol);
  const si = head.indexOf(cfg.stateCol);
  if (ti < 0 || si < 0) throw new Error(`${cfg.name}: missing column ${cfg.tsCol}/${cfg.stateCol}`);
  const rows: RawRow[] = [];
  const bad: BadRow[] = [];
  lines.slice(1).forEach((l, i) => {
    const line = i + 2; // เลขบรรทัดในไฟล์ (บรรทัด 1 คือหัวตาราง)
    const cols = l.split(",");
    try {
      const p = parseTimestamp(cols[ti] ?? "", cfg.assumedOffsetMin);
      rows.push({ line, ms: p.ms, state: (cols[si] ?? "").trim(), flags: p.flags });
    } catch (e) {
      bad.push({ line, text: l, why: (e as Error).message });
    }
  });
  return { rows, bad };
}
ingest: rows whose time cannot be read go into bad, with the line number and the reason

The example does not delete bad rows and does not try to guess them. The row is kept in the report with the line where it occurred. Whoever looks after the gateway can use that to trace what value the device wrote.

Step 4: Sort, remove duplicates, snap to the grid and count what changed

Data that can be read still has out-of-order rows, duplicate rows, and times that are a few seconds off a whole minute. This function flags every row it touches and counts them in the report. The rules: rows with the same time and the same state count as identical duplicates. Rows with the same time but conflicting states keep the first row in the file, and the report records that a row was dropped. Once the user sees the flag, they can decide which row to trust. A row is snapped to the grid only when it is within the allowed tolerance (5 seconds). Anything else is off_grid.

series.ts · lines 18–67
export function cleanSeries(rows: RawRow[], o: Opts): { points: Point[]; report: SeriesReport } {
  const report: SeriesReport = { inputRows: rows.length, outOfOrder: 0, dupIdentical: 0, dupConflict: 0, snapped: 0, maxSnapMs: 0, offGrid: 0, gaps: [] };

  let maxSeen = -Infinity;
  const tagged = rows.map((r) => {
    const flags = [...r.flags];
    if (r.ms < maxSeen) {
      flags.push("out_of_order");
      report.outOfOrder++;
    }
    maxSeen = Math.max(maxSeen, r.ms);
    return { r, flags };
  });
  tagged.sort((a, b) => a.r.ms - b.r.ms); // sort เสถียร: แถวที่ ts เท่ากันคงลำดับในไฟล์

  const byTs = new Map<number, Point>();
  for (const { r, flags } of tagged) {
    let ts = r.ms;
    let shiftMs = 0;
    const slot = Math.round((r.ms - o.origin) / o.period) * o.period + o.origin;
    if (Math.abs(slot - r.ms) <= o.snapTol) {
      shiftMs = slot - r.ms;
      ts = slot;
      if (shiftMs !== 0) {
        report.snapped++;
        report.maxSnapMs = Math.max(report.maxSnapMs, Math.abs(shiftMs));
        flags.push(`snapped_${shiftMs}ms`);
      }
    } else {
      report.offGrid++;
      flags.push("off_grid");
    }
    const kept = byTs.get(ts);
    if (!kept) byTs.set(ts, { ts, state: r.state, flags, line: r.line, shiftMs });
    else if (kept.state === r.state) {
      report.dupIdentical++;
      kept.flags.push(`dup_identical_line${r.line}`);
    } else {
      report.dupConflict++;
      kept.flags.push(`dup_conflict_line${r.line}_dropped_${r.state}`);
    }
  }

  const points = [...byTs.values()].sort((a, b) => a.ts - b.ts);
  for (let i = 1; i < points.length; i++) {
    const missing = Math.round((points[i].ts - points[i - 1].ts) / o.period) - 1;
    if (missing > 0) report.gaps.push({ fromTs: points[i - 1].ts + o.period, missing });
  }
  return { points, report };
}
cleanSeries: every fix has a flag and a counter in the report

simplified: Keeping the first row in the file when values conflict is a rule of this example, not a universal rule. Some systems trust the row received later, and some pass it to a person to decide. Agree on the rule with the data owner before using it for real.

Step 5: Separate machine-off periods from missing data

A period with no rows in one source can mean the machine was really off, or it can mean the gateway dropped out. These two must not be counted the same way. The example's rule is strict on purpose. A gap is machine_off only if every other source has a value at every point of that period and all of them are OFF. If another source sees STOP or RUN, or also has no data, the period is no_data, because we do not know what the machine was doing.

align.ts · lines 20–46
// ช่วงขาดของแหล่ง S เป็น machine_off ก็ต่อเมื่อแหล่งอื่น "ทุกจุดในช่วงนั้น" มีค่าและเป็น OFF ทั้งหมด
// นอกนั้นเป็น no_data (ไม่รู้ว่าเครื่องทำอะไร) ห้ามเดาว่าเครื่องดับ
export function classifyGaps(cells: Record<string, Cell[]>): Gap[] {
  const gaps: Gap[] = [];
  for (const [name, col] of Object.entries(cells)) {
    let i = 0;
    while (i < col.length) {
      if (col[i].state !== null) { i++; continue; }
      let j = i;
      while (j < col.length && col[j].state === null) j++;
      const peerStates = new Set<string>();
      let allCovered = true;
      for (const [other, oc] of Object.entries(cells)) {
        if (other === name) continue;
        for (let k = i; k < j; k++) {
          const s = oc[k].state;
          if (s === null) allCovered = false;
          else peerStates.add(s);
        }
      }
      const off = allCovered && peerStates.size === 1 && peerStates.has("OFF");
      gaps.push({ source: name, fromIdx: i, count: j - i, kind: off ? "machine_off" : "no_data", peers: [...peerStates].sort().join("/") || "-" });
      i = j;
    }
  }
  return gaps;
}
classifyGaps: does not assume the machine was off unless another source confirms it

Next, the three sources are merged by priority. The value from the first source that has data is used. If a value has to be taken from another source, it gets a filled_from_ flag, and if another source disagrees, it gets a conflict_ flag. The user can filter to see only the rows that did not come from the primary source.

align.ts · lines 48–61
// priority: แหล่งแรกในลิสต์ที่มีค่า ถ้าใช้แหล่งที่ไม่ใช่ลำดับแรกให้ flag filled_from และถ้าแหล่งอื่นเห็นต่างให้ flag conflict
export function merge(grid: number[], cells: Record<string, Cell[]>, priority: string[]): Merged[] {
  return grid.map((ts, i) => {
    const flags: string[] = [];
    const chosen = priority.find((n) => cells[n][i].state !== null) ?? null;
    if (chosen === null) return { ts, state: null, from: null, flags: ["no_source"] };
    if (chosen !== priority[0]) flags.push(`filled_from_${chosen}`);
    for (const n of priority) {
      const s = cells[n][i].state;
      if (n !== chosen && s !== null && s !== cells[chosen][i].state) flags.push(`conflict_${n}_${s}`);
    }
    return { ts, state: cells[chosen][i].state, from: chosen, flags };
  });
}
merge: can fill from a backup source, but must always say where the value came from

Step 6: Count downtime minutes per shift

Shift A is 06:00-14:00, shift B is 14:00-22:00 and shift C is 22:00-06:00, Thai time. Times from 00:00 to 05:59 count as shift C of the previous day. This is where many reports go wrong, because they split by calendar day. The example counts STOP, RUN, OFF and unknown separately, so periods without data do not vanish from the report.

kpi.ts · lines 4–25
export function shiftOf(ms: number): string {
  const t = new Date(ms + 7 * 3600_000);
  const h = t.getUTCHours();
  const label = h >= 6 && h < 14 ? "A" : h >= 14 && h < 22 ? "B" : "C";
  if (h < 6) t.setUTCDate(t.getUTCDate() - 1); // 00:00-05:59 นับเป็นกะ C ของวันก่อน
  return `${t.toISOString().slice(0, 10)} ${label}`;
}

export function byShift(points: { ts: number; state: string | null }[], periodMs: number): Map<string, Bucket> {
  const out = new Map<string, Bucket>();
  const min = periodMs / 60_000;
  for (const p of points) {
    const k = shiftOf(p.ts);
    const b = out.get(k) ?? { stop: 0, run: 0, off: 0, unknown: 0 };
    if (p.state === "STOP") b.stop += min;
    else if (p.state === "RUN") b.run += min;
    else if (p.state === "OFF") b.off += min;
    else b.unknown += min;
    out.set(k, b);
  }
  return new Map([...out].sort());
}
shiftOf and byShift: the unknown period is not silently counted as zero

Real run: results from the simulated data

The main script loads the event pairs to estimate the HMI drift, then runs the three sources through steps 1-5. It prints a report per source, the gaps, the flagged rows and each KPI variant. These two functions connect the layers.

check.ts · lines 24–37
function loadFit(): ClockFit {
  const lines = read("sync_pairs.csv").trim().split("\n").slice(1);
  return fitClock(lines.map((l) => {
    const [d, r] = l.split(",");
    return { device: parseTimestamp(d, 420).ms, ref: parseTimestamp(r, 0).ms };
  }));
}

function load(cfg: SourceConfig, opt: { assumedOffsetMin?: number; fit?: ClockFit }) {
  const { rows, bad } = ingest(read(cfg.file), { ...cfg, assumedOffsetMin: opt.assumedOffsetMin ?? cfg.assumedOffsetMin });
  const fixed = opt.fit ? rows.map((r) => ({ ...r, ms: Math.round(toReference(opt.fit!, r.ms)), flags: [...r.flags, "drift_corrected"] })) : rows;
  const count = (f: string) => rows.filter((r) => r.flags.includes(f)).length;
  return { ...cleanSeries(fixed, opts), bad, naive: count("naive_assumed_offset"), be: count("be_year") };
}
loadFit estimates the drift from event pairs. load reads, corrects the drift (HMI only) and cleans
output.txt
== นาฬิกา HMI เทียบนาฬิกาอ้างอิง (gateway ที่ sync NTP) ==
คู่เหตุการณ์ 6 คู่  offset ณ ช่วงที่ตรวจ (2026-03-02 13:30 ไทย) = 110.5 s (HMI เร็วกว่าอ้างอิง)
drift = 25.0 ppm  residual สูงสุด = 680 ms

== รายงานต่อแหล่ง ==
[gateway] แถวอ่านได้ 58  แถวเสีย 0  naive(เดาโซน) 0  ปี พ.ศ. 0  สลับลำดับ 1
   ซ้ำเหมือนกัน 1  ซ้ำแต่ค่าขัด 0  ขยับเข้าตาราง 0 (สูงสุด 0 ms)  นอกตาราง 0
   ช่วงขาด: 13:55:00 x3
[historian] แถวอ่านได้ 58  แถวเสีย 1  naive(เดาโซน) 5  ปี พ.ศ. 0  สลับลำดับ 0
   ซ้ำเหมือนกัน 0  ซ้ำแต่ค่าขัด 1  ขยับเข้าตาราง 0 (สูงสุด 0 ms)  นอกตาราง 0
   ช่วงขาด: 14:12:00 x3
   แถวเสียบรรทัด 8: unrecognised timestamp: "N/A"
[hmi] แถวอ่านได้ 55  แถวเสีย 0  naive(เดาโซน) 55  ปี พ.ศ. 55  สลับลำดับ 0
   ซ้ำเหมือนกัน 0  ซ้ำแต่ค่าขัด 0  ขยับเข้าตาราง 55 (สูงสุด 539 ms)  นอกตาราง 0
   ช่วงขาด: 14:20:00 x5

== ช่วงที่ขาดบนตารางเวลา 1 นาที (13:30-14:29) ==
gateway   13:55:00 x3  no_data  (แหล่งอื่นเห็น: STOP)
historian 14:12:00 x3  no_data  (แหล่งอื่นเห็น: RUN)
hmi       14:20:00 x5  machine_off  (แหล่งอื่นเห็น: OFF)

== ชุดที่จัดแนวแล้ว เฉพาะแถวที่มี flag ==
13:55:00  -     STOP  STOP  -> STOP  filled_from_historian
13:56:00  -     STOP  STOP  -> STOP  filled_from_historian
13:57:00  -     STOP  STOP  -> STOP  filled_from_historian
14:12:00  RUN   -     RUN   -> RUN   
14:13:00  RUN   -     RUN   -> RUN   
14:14:00  RUN   -     RUN   -> RUN   
14:20:00  OFF   OFF   -     -> OFF   
14:21:00  OFF   OFF   -     -> OFF   
14:22:00  OFF   OFF   -     -> OFF   
14:23:00  OFF   OFF   -     -> OFF   
14:24:00  OFF   OFF   -     -> OFF   

== KPI: นาทีหยุดเครื่อง (STOP) ต่อกะ  ความจริงในข้อมูลจำลอง = กะ A 10 นาที, กะ B 10 นาที ==
HMI: อ่านเวลาเป็น UTC (ลืมโซน)               03-02 B stop=20 unknown=0
HMI: แก้โซนแล้ว ยังไม่แก้นาฬิกาเพี้ยน        03-02 A stop=9 unknown=0 | 03-02 B stop=11 unknown=0
HMI: แก้โซนและนาฬิกาเพี้ยน                   03-02 A stop=10 unknown=0 | 03-02 B stop=10 unknown=0
gateway อย่างเดียว (มีช่วงขาดกลาง STOP)      03-02 A stop=7 unknown=3 | 03-02 B stop=10 unknown=0
รวมสามแหล่ง ลำดับ gateway>historian>hmi      03-02 A stop=10 unknown=0 | 03-02 B stop=10 unknown=0
Output of a real run on 2026-11-21 with node check.ts (Node 24). The MODULE_TYPELESS_PACKAGE_JSON warning goes to stderr and is not in this file
  1. The top says the HMI is 110.5 seconds ahead of the reference clock at the time checked, with a drift of 25.0 ppm, which matches what was set in the simulated data. The maximum residual of 680 ms is much smaller than the 1-minute resolution, so the straight line is good enough for this job.
  2. The gateway has 1 out-of-order row, 1 identical duplicate and a three-minute gap at 13:55. The historian has 1 bad row at line 8 (N/A), 5 naive rows, 1 duplicate with conflicting values and a three-minute gap at 14:12.
  3. The HMI read 55 rows. All of them are naive, the Buddhist Era year was converted, 55 rows were snapped to the grid (farthest 539 ms), and it is missing five minutes from 14:20.
  4. The gaps fall into three kinds. The gateway gap at 13:55 is no_data because other sources see STOP, so the machine was still stopped. The historian gap at 14:12 is no_data because other sources see RUN. The HMI gap at 14:20 is machine_off because the other two sources see OFF at every minute.
  5. The aligned set shows only the rows that need a look. 13:55-13:57 was filled from the historian with the flag filled_from_historian, and the period 14:20-14:24 is missing only from the HMI.
  6. The KPI is the heart of it. The truth is 10 minutes in shift A and 10 minutes in shift B. If the HMI time is read as UTC (forgetting the zone), the result is 20 minutes in shift B and none in shift A. If the zone is fixed but the clock drift is not, the result is A 9 and B 11, because 110 seconds pushes some minutes across the shift boundary. If only the gateway is used, the result is A 7 and unknown 3, because the gap falls in the middle of the STOP. Once everything is fixed and the three sources are merged, the result is A 10 and B 10, which matches the truth.

Notice that the wrong KPI comes in three kinds, with three different causes: the zone, the clock, and missing data. Each needs a different fix.

The test suite: what it checks

The test suite checks.test.ts has 8 cases, run with node --test checks.test.ts. All of them passed when the article was written. Here are two cases that check the easiest places to go wrong.

checks.test.ts · lines 44–53
test("cleanSeries: สลับลำดับ ซ้ำ ซ้ำขัดกัน และช่วงขาด ถูกนับและไม่หายเงียบ", () => {
  const rows = [row(0, "RUN"), row(2, "RUN"), row(1, "RUN"), row(2, "RUN"), row(3, "STOP"), row(3, "RUN"), row(7, "RUN")];
  const { points, report } = cleanSeries(rows, o);
  assert.equal(report.outOfOrder, 1); // มีแค่แถวเวลา 1 ที่มาหลังแถวเวลา 2
  assert.equal(report.dupIdentical, 1);
  assert.equal(report.dupConflict, 1);
  assert.deepEqual(report.gaps, [{ fromTs: T + 4 * 60_000, missing: 3 }]);
  assert.equal(points.find((p) => p.ts === T + 3 * 60_000)!.state, "STOP"); // เก็บแถวแรกในไฟล์
  assert.ok(points.find((p) => p.ts === T + 3 * 60_000)!.flags.some((f) => f.startsWith("dup_conflict")));
});
Out-of-order rows, duplicates, conflicting duplicates and gaps must be counted and must not disappear silently
checks.test.ts · lines 64–72
test("classifyGaps: machine_off ต้องมีแหล่งอื่นยืนยัน OFF ทุกจุด ไม่งั้นเป็น no_data", () => {
  const c = (...s: (string | null)[]): Cell[] => s.map((state) => ({ state, flags: [] }));
  const g1 = classifyGaps({ a: c("RUN", null, null), b: c("RUN", "OFF", "OFF"), c: c("RUN", "OFF", "OFF") });
  assert.equal(g1[0].kind, "machine_off");
  const g2 = classifyGaps({ a: c("RUN", null, null), b: c("RUN", "OFF", "RUN") });
  assert.equal(g2[0].kind, "no_data");
  const g3 = classifyGaps({ a: c("RUN", null, null), b: c("RUN", "OFF", null) });
  assert.equal(g3[0].kind, "no_data"); // แหล่งอื่นก็ไม่มีข้อมูลที่จุดสุดท้าย
});
machine_off needs confirmation from other sources at every point, otherwise it is no_data

The remaining cases check parseTimestamp for both accepted and rejected input, fitClock recovering a known offset and drift, snapping to the grid, merge, and the shift boundaries at 14:00 and shift C crossing midnight.

Using it for real: what this example leaves out

  • Store time as UTC in the time-series database, for example in a time-zone-aware column type (timestamptz in PostgreSQL), not as text. Convert to Thai time only for display or for the per-shift summary.
  • Keep the event time, the ingestion time and a data quality status (good/filled/missing) as separate columns. Do not merge them, and do not overwrite the raw value.
  • Read large files line by line (stream) instead of loading the whole file, and use a real CSV reader that supports quoting and file encoding.
  • If the collection interval is not one minute, set the period and the allowed tolerance for each source. Also check whether each source samples on a timer or records only when the value changes (on change), because the way you find gaps is different.
  • Sync the gateway and server clocks with NTP, and monitor the offset as a value that must raise an alert. If the job needs event order below one millisecond, look at PTP and hardware that supports it.
  • Collect the event pairs for estimating drift automatically, for example by writing the device time against the reference time every night, not by having someone note it while walking past.
  • When you correct data after the fact, keep the original value, the corrected value and the reason, so it can be audited.

Adapting it to your business

Energy per unit produced per shift

If you divide energy by the number of pieces per shift, both sides must use the same shift boundary. If the energy meter and the piece counter use different clocks, the numerator and the denominator land in different shifts. This example can be used as a check step before the calculation.

Downtime for OEE and MTTR

Downtime and repair time are the basis of availability metrics. If gaps are counted as zero, the figures look better than they really are. Separating out no_data lets the report say how many minutes are unknown, instead of pretending to know.

Collecting data from older machines

Older machines often have no clock that can sync. A gateway added later should do the timestamping, and it should record that the time is ingestion time, not event time. A difference of tens of milliseconds to a second usually does not affect per-shift reports. But if several gateways have to be compared, measure the clock difference first.

Common mistakes

  • Guessing the offset silently and not adding a flag, so you cannot tell which rows are less reliable.
  • Changing a device's time in a production system without a plan. This can affect scheduled job logs and the relationships with existing data. Change the time in steps and test first.
  • Counting periods with no data as zero or as machine off, without confirming with other sources.
  • Splitting shifts by calendar date, so 00:00-05:59 falls into the next day.
  • Using file order instead of time order, and forgetting that a device that buffers data will send it all at once later.
  • Filling a value from a backup source without recording where it came from.
  • Believing NTP is accurate to the microsecond everywhere. The figures in the documents depend on a good network and good machines. Measure it in your own factory.

Checklist before real use

  1. State for each source whether its time is event time or ingestion time, who stamps it, and where the clock comes from.
  2. Check the time format of every source: with or without offset, C.E. or B.E. year, day/month order.
  3. Set up NTP on every machine that stamps time, and monitor the offset.
  4. Collect event pairs to estimate the drift of devices that cannot sync, and look at the residual.
  5. On every import, report the count of bad rows, duplicates, out-of-order rows and times snapped to the grid.
  6. Separate machine_off from no_data, and have the KPI show unknown minutes on their own.
  7. Test with a period of data where the truth is known, for example a simulated event with a known reference time, and compare the per-shift figures.

Monitoring after go-live

Have the system measure these values continuously: each machine's clock offset against the reference, the number of bad rows per day, the longest gap, and the share of no_data minutes per shift. Raise an alert when any value passes the threshold the team agreed on, so you find out before the report goes wrong.

Limits: The example is a learning tool. It uses made-up data and a single straight-line drift model. The accuracy figures for NTP, PTP and chrony in the article come from the documents of the standard's authors or the developers themselves, not from measurements in any factory. Before using it on a production system, test it with real devices and a real network, and check the time-setting procedure against the manual of each device model's manufacturer.

References

  1. IETF RFC 3339 — Date and Time on the Internet: Timestamps (Z, numeric offset, -00:00) (accessed 2026-11-21)
  2. IETF RFC 5905 — Network Time Protocol Version 4 (protocol and algorithms) (accessed 2026-11-21)
  3. chrony — Comparison of NTP implementations (PTP reference clock, hardware timestamping) (accessed 2026-11-21)
  4. IEEE 1588-2019 — Precision Time Protocol (PTP) for networked measurement and control systems (accessed 2026-11-21)
  5. OPC UA Part 4 — 7.11.3 SourceTimestamp (UTC) (accessed 2026-11-21)
  6. Wikipedia — Thai solar calendar (Buddhist Era = CE + 543, year starts 1 January since 1941) (accessed 2026-11-21)
  7. Node.js — Test runner (node --test) (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer