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.
Code
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
Age CalculatorCalculate exact age in years, months, and days between a birth date and a reference date, plus total days and the next birthday countdown.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.Business Days CalculatorCount the weekdays between two dates, excluding weekends and any holidays you list, and see how many calendar and weekend days are involved.Cron Next Runs CalculatorCompute the next scheduled run times for a standard five-field cron expression, supporting ranges, lists, steps, and day-of-week naming semantics.
FAQ
- What does this need from the package registry?
- These are real dependencies: `email`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.