Converting Time or Datetime to UTC in Python

This seems so basic, it’s almost embarrassing to publish, but this showed up a few times on Stackexchange. I had trouble figuring it out, too, partly because the Python docs are so lengthy.

The scenario: you have a textual timestamp with a timezone, and need to convert it to UTC. I had the former in and email date header, and needed it printed in UTC for the envelope.

The input looks like this:
Tue, 17 Mar 2009 18:57:55 -0300

from dateutil.parser import parse
from datetime import timezone, datetime, timedelta

t = parse("Tue, 17 Mar 2009 18:57:55 -0300")

## first way
tu = t.astimezone(timezone.utc)

## second way
tu = datetime.utcfromtimestamp(t.timestamp())

## and as text
text = tu.strftime("%c")

The main difference between the first and second ways is that the first way strips off the timezone info (tzinfo), so it become a “naive” datetime. The second way sets the tzinfo to utc, which is better.

Also, the Date lines in email headers varies, and taking a slice of [6:37] will chop off timezone markings like “(GMT-08:00)” that cause the parser to barf.