Converting time_struct with timezone to datetime GMT in Python

Viewed 635

I'm retrieving struct_time dates from Feedparser.

Like you can see below, FeedParser automatically parses the dates into GMT (second line, EDT, get converted from 19:19 to 23:19)

FeedParser converted Sun, 06 Sep 2020 23:07:16 GMT into struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))

FeedParser converted Fri, 11 Sep 2020 19:19:01 EDT into struct_time((2020, 9, 11, 23, 19, 1, 4, 255, 0))

When I try to convert the struct_time to a datetime with the below, I get GMT + 1 (my timezone).

from datetime import datetime
from time import mktime
datetime.fromtimestamp(mktime(struct_time((2020, 9, 6, 23, 7, 16, 6, 250, 0))))
> datetime.datetime(2020, 9, 7, 0, 7, 16)

How can I convert these struct_time into datetimes GMT?

1 Answers

to get a time zone aware datetime object, you could unpack the relevant part of the timetuple into a datetime object and set the tzinfo attribute to UTC:

from datetime import datetime, timezone

# given a time_struct tuple like
s = (2020, 9, 6, 23, 7, 16, 6, 250, 0)
# convert to datetime object as
dt = datetime(*s[:6], tzinfo=timezone.utc)
print(dt)
>>> 2020-09-06 23:07:16+00:00
Related