Skip to content
Require an explicit offset when normalizing email dates

Require an explicit offset when normalizing email dates

November 23, 2026

An email date parser can return either an aware or a naive datetime. An importer that requires a stated source offset should check that result before converting timestamps to UTC.

Run the example

Tested on Linux with Python 3.12.14 and Python 3.13.5. Use one Bash session and a text editor. Create a disposable working directory before saving the source:

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Save as demo_python_email_date_explicit_offset_policy.py:

from datetime import timezone
from email.utils import parsedate_to_datetime

def normalize(text):
    value = parsedate_to_datetime(text)
    if value.tzinfo is None or value.utcoffset() is None:
        raise ValueError("explicit source offset required")
    return value.astimezone(timezone.utc)

for text in ("Fri, 21 Nov 1997 09:55:06 -0600",
             "Fri, 21 Nov 1997 15:55:06 +0000",
             "Fri, 21 Nov 1997 15:55:06 -0000"):
    try:
        value = normalize(text)
    except ValueError as error:
        print("Rejected:", error)
    else:
        print(value.isoformat())

Run it:

python3 -B demo_python_email_date_explicit_offset_policy.py

Observed output:

1997-11-21T15:55:06+00:00
1997-11-21T15:55:06+00:00
Rejected: explicit source offset required

The first two inputs identify the same instant with explicit offsets. For a conforming email date, -0000 represents UTC while withholding the original source time zone; Python returns a naive datetime for it. This importer deliberately rejects that case because its policy requires an explicit source offset.

Limits and input policy

That rejection is an application policy, not a claim that -0000 is an invalid email date. Another importer can preserve its documented UTC meaning while recording that the source zone was unspecified. Avoid calling astimezone() on an unchecked naive value: Python can interpret it using the machine local zone. Parsing also does not authenticate a sender or establish that the stated time is truthful.

Clean up

Remove the saved script and the empty working directory in the same Bash session:

rm -- demo_python_email_date_explicit_offset_policy.py
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

If the directory is not empty, inspect its contents before removing anything else.

Reference

Official documentation

Acknowledgements

This post was created with assistance from AI.

Last updated on