email.utils Formats RFC 2822 Dates

Format and parse email timestamps with email.utils, compare timezone offsets, and render the GMT label required by message headers.

PythonData Integrity

Code

pythonsnippet
26 lines
from datetime import datetime, timedelta, timezone
from email.utils import format_datetime, parsedate_to_datetime


def main() -> None:
    # RFC 2822 date headers use this textual timestamp format.
    moment = datetime(2026, 11, 17, 9, 30, tzinfo=timezone.utc)
    header = format_datetime(moment)
    print("header:", header)

    parsed = parsedate_to_datetime(header)
    print("parsed:", parsed.isoformat())
    print("matches:", parsed == moment)

    offset = timezone(timedelta(hours=8))
    local = datetime(2026, 11, 17, 17, 30, tzinfo=offset)
    print("offset header:", format_datetime(local))
    same_instant = parsedate_to_datetime(format_datetime(local)) == moment
    print("same instant:", same_instant)

    # usegmt renders the GMT zone label required by some headers.
    print("gmt:", format_datetime(moment, usegmt=True))


if __name__ == "__main__":
    main()

How it works

email.utils Formats RFC 2822 Dates is built around the function main.

From email it pulls datetime, timedelta, timezone, format_datetime, parsedate_to_datetime — the imports name exactly which library surface the snippet touches.

What to watch for

  • External dependency: email — install it before running the snippet.

Putting it to use

The main signature reads def main() -> None

The run emits 6 labeled sections — header:, parsed:, matches:, offset header:, same instant:, gmt: — one per step.

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `email`. Without it the snippet will not load.