Skip to content

email.utils.format_datetime rejects custom zero-offset tzinfo with usegmt=True #158782

Description

@augusto-rehfeldt

Bug report

Bug description:

Documented behaviour: The format_datetime docstring states: "If usegmt is True, dt must be an aware datetime with an offset of zero. In this case 'GMT' will be rendered instead of the normal +0000 required by RFC2822."

Expected: Return a date string ending in ' GMT' without raising ValueError for an aware zero-offset datetime.

Actual: Raises ValueError: usegmt option requires a UTC datetime.

import datetime as d
import email.utils

class ZeroOffset(d.tzinfo):
    def utcoffset(self, dt): return d.timedelta(0)
    def dst(self, dt): return d.timedelta(0)
    def tzname(self, dt): return "UTC"
    def __repr__(self): return "ZeroOffset()"

dt = d.datetime(1, 1, 1, tzinfo=ZeroOffset())
if dt.tzinfo is None or dt.utcoffset() != d.timedelta(0):
    print("REFUTATION REJECTED: input is not aware with zero offset")
else:
    expected = (
        f"{('Mon','Tue','Wed','Thu','Fri','Sat','Sun')[dt.weekday()]}, "
        f"{dt.day:02d} {'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split()[dt.month-1]} "
        f"{dt.year:04d} {dt.hour:02d}:{dt.minute:02d}:{dt.second:02d} GMT"
    )
    try:
        actual = ("result", email.utils.format_datetime(dt, usegmt=True))
    except Exception as e:
        actual = ("exception", type(e).__name__, str(e))
    if actual != ("result", expected):
        print("REFUTATION CONFIRMED:", repr(dt), "actual:", actual, "expected:", repr(expected))
    else:
        print("REFUTATION REJECTED: result matches documented expectation")

Output on Python 3.14.6 (Windows-11-10.0.26220-SP0), standard library email.utils:

REFUTATION CONFIRMED: datetime.datetime(1, 1, 1, 0, 0, tzinfo=ZeroOffset()) actual: ('exception', 'ValueError', 'usegmt option requires a UTC datetime') expected: 'Mon, 01 Jan 0001 00:00:00 GMT'

This report was found and written by an automated property-testing tool I run (bugforge). The reproducer above was executed and its output is pasted unedited; no person reviewed the report before it was filed. The search script is in https://github.com/augusto-rehfeldt/bugforge-results/tree/main/email.utils-20261003-021105-c3

CPython versions tested on:

3.14

Operating systems tested on:

Windows

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions