Temporal Reasoning: When Did It Happen?
Module: Natural Language Processing | Difficulty: Advanced
What You'll Learn
- 1Normalize surface time expressions into ISO 8601 intervals
- 2Classify pairwise event relations over the Allen interval set
- 3Apply transitive closure to complete a partially labeled timeline
- 4Read accuracy and macro-F1 gaps for simultaneous versus ordered events
Temporal reasoning recovers the timeline hidden in a document: which event came first, how long it lasted, and what a phrase like "two weeks earlier" resolves to. Almost every downstream task that must answer "what happened next" or "was the debt repaid before the audit" depends on it. This lesson normalizes time expressions, classifies pairwise event relations with the interval algebra, and completes partial timelines with transitive closure.
Time Expressions and Normalization
Surface expressions come in three kinds: absolute dates such as March 1, 2024, relative expressions such as two weeks later, and vague ones such as last spring. Normalization converts each TIMEX3 span into an ISO 8601 value, either a point or an interval with start and end, which is what tools such as SUTime (Chang and Manning, 2012) emit.
| Relation | Test on intervals | Inverse |
|---|---|---|
| before | after | |
| meets | metBy | |
| overlaps | overlappedBy | |
| during | and | contains |
| equals | and | equals |
Closure over a partial timeline
Prediction yields a sparse graph, but time is transitive: if A precedes B and B precedes C, then A precedes C with no model involved. Applying closure to a directed BEFORE graph turns observed edges into the full order, and any resulting cycle marks a contradiction worth reporting to the annotator.
Timeline construction as a scoring problem
Given events with candidate intervals and a set of pairwise predictions, timeline construction selects the assignment that maximizes total relation score while keeping the graph acyclic, which makes it a weighted DAG problem solvable by topological ordering rather than search.
Worked Code
from datetime import date, timedelta
MONTHS = {m.lower(): i for i, m in enumerate(
["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"], start=1)}
DUR = {"day": 1, "days": 1, "week": 7, "weeks": 7,
"month": 30, "months": 30, "year": 365, "years": 365}
def normalize(text, doc_date):
"""Resolve absolute and relative date expressions to ISO 8601."""
low = text.lower()
if "today" in low:
return doc_date.isoformat()
if "yesterday" in low:
return (doc_date - timedelta(days=1)).isoformat()
words = low.replace(",", " ").split()
for i, w in enumerate(words):
if w in MONTHS and i + 2 < len(words) and words[i + 1].isdigit():
d, y = int(words[i + 1]), int(words[i + 2])
return date(y, MONTHS[w], d).isoformat()
number = {"a": 1, "an": 1, "one": 1, "two": 2, "three": 3, "four": 4,
"five": 5, "six": 6, "seven": 7, "eight": 8, "nine": 9,
"ten": 10, "fourteen": 14, "twenty": 20, "thirty": 30}
for i, w in enumerate(words):
if w in number and i + 1 < len(words) and words[i + 1] in DUR:
days = number[w] * DUR[words[i + 1]]
span = timedelta(days=days)
if "after" in words or "later" in words:
return (doc_date + span).isoformat()
if "before" in words or "earlier" in words:
return (doc_date - span).isoformat()
return None
DOC = date(2024, 3, 1)
PHRASES = ["March 15, 2024", "fourteen weeks after", "two weeks earlier",
"yesterday", "today"]
for p in PHRASES:
print(f"{p:22s} -> {normalize(p, DOC)}")
run_start = date(2024, 3, 1)
run_end = run_start + timedelta(weeks=14)
print("14-week run:", run_start.isoformat(), "to", run_end.isoformat())
COMPOSE = {
("BEFORE", "BEFORE"): "BEFORE",
("AFTER", "AFTER"): "AFTER",
("BEFORE", "SIMULTANEOUS"): "BEFORE",
("SIMULTANEOUS", "BEFORE"): "BEFORE",
("AFTER", "SIMULTANEOUS"): "AFTER",
("SIMULTANEOUS", "AFTER"): "AFTER",
("SIMULTANEOUS", "SIMULTANEOUS"): "SIMULTANEOUS",
}
def closure(edges):
"""Propagate pairwise labels; returns all facts plus contradictions."""
facts, conflicts = {}, []
for a, b, r in edges:
if (a, b) in facts and facts[(a, b)] != r:
conflicts.append(((a, b), facts[(a, b)], r))
else:
facts.setdefault((a, b), r)
changed = True
while changed:
changed = False
for (a, b), r1 in list(facts.items()):
for (c, d), r2 in list(facts.items()):
if b != c or a == d:
continue
composed = COMPOSE.get((r1, r2))
if composed is None:
continue
key = (a, d)
if key in facts:
if facts[key] != composed and (key, facts[key], composed) not in conflicts:
conflicts.append((key, facts[key], composed))
else:
facts[key] = composed
changed = True
return facts, conflicts
edges = [("speak", "arrive", "BEFORE"), ("arrive", "seat", "BEFORE"),
("seat", "applaud", "BEFORE"), ("arrive", "seat", "SIMULTANEOUS")]
facts, conflicts = closure(edges)
print("facts after closure:", len(facts))
for (a, b), r in sorted(facts.items()):
print(f" {a:8s} {r:14s} {b}")
print("conflicts:", conflicts)
gold = {("speak", "arrive"): "BEFORE", ("speak", "seat"): "BEFORE",
("speak", "applaud"): "BEFORE", ("arrive", "applaud"): "BEFORE",
("applaud", "leave"): "BEFORE"}
hits = sum(1 for k, v in gold.items() if facts.get(k) == v)
print("closure accuracy on gold:", round(hits / len(gold), 3))
Real-World Applications
- TimeBank annotates about 1,467 news documents with events and TIMEX3 spans, the reference corpus for relation classification.
- MATRES supplies roughly 8,600 event pairs across 2,381 documents, which is what made dense temporal annotation affordable to train on.
- DocTimeLine provides gold timelines for 2,201 documents, so timeline reconstruction can be scored directly rather than inferred from pairwise accuracy.
- SUTime-style normalizers handle the vague case that dominates real text: expressions such as last spring resolve through the document's own date anchor.
â ī¸No anchor, no timeline
Common Mistakes
Classifying pairs without normalizing intervals first
Fix: Normalize every TIMEX3 and event to ISO 8601 bounds; only then does a relation reduce to comparing start and end times
Reporting accuracy while hiding the simultaneous class
Fix: Publish macro-F1 and per-class F1, since SIMULTANEOUS routinely trails by 10 to 15 points and drags the average
Skipping consistency checks on the final timeline
Fix: Run transitive closure and flag cycles, because a cycle means the model produced an impossible order that no reader can reconcile
Best Practices
- Normalize to intervals with explicit start and end, not to single points
- Apply transitive closure after classification and report how many relations closure added
- Anchor every relative expression to the document date before comparing intervals
Key Takeaways
- TIMEX3 spans normalize to ISO 8601 points or intervals relative to a document anchor
- Allen's thirteen interval relations reduce temporal classification to comparing four timestamps
- Transitive closure expands O(n) observed edges into the full O(n^2) order and detects contradictions
- Simultaneity trails before and after by roughly 13 points because it requires duration, not just order
Frequently Asked Questions
What corpora are standard?
TimeBank carries about 1,467 news documents with event and time annotations, MATRES adds roughly 8,600 event pairs over 2,381 documents, and DocTimeLine provides gold timelines for 2,201 documents.
Why is SIMULTANEOUS harder than BEFORE?
Because ordering can be inferred from narration order and tense, whereas simultaneity requires knowing that two intervals overlap in duration. Predicted durations are usually coarse, so the class trails by 10 to 15 F1.
Does closure improve accuracy or only consistency?
It can do both. Closure adds relations the model never scored, which raises recall on gold pairs, and it surfaces cycles that flag annotation errors, which is valuable even when accuracy does not move.
Interview Questions
Q1: How do you normalize 'fourteen weeks after March 1'?
Anchor to the document date, convert the duration to 98 days, and add it to 2024-03-01, giving 2024-06-07; store the result as an interval, not a point
Q2: What does transitive closure do to a temporal graph?
It composes labeled edges so BEFORE-AFTER chains propagate: with n events the reachable order grows toward n(n-1)/2 pairs, and any cycle is a contradiction