I'd like to know how to convert an EST Datetime string (e.g., '2020-02-02 09:30:00') to a UTC Timestamp with Python 3, without using external libraries such as pytz which gave me an inaccurate EST to UTC conversion.
Asked
Active
Viewed 1,268 times
0
-
1Can you share the innacurate conversion pytz gave you? – Nilo Araujo Jul 14 '22 at 14:47
-
you mean [Weird timezone issue with pytz](https://stackoverflow.com/q/11473721/10197418)? I've added some more up-to-date options [there](https://stackoverflow.com/a/71668778/10197418)... – FObersteiner Jul 14 '22 at 14:56
-
It was 6 minutes less than the accurate conversion. – Lex Jul 14 '22 at 15:17
-
1Sounds like you did not `localize` and got LMT. Anyways, pytz is deprecated and you have zoneinfo, as below answer shows. – FObersteiner Jul 14 '22 at 15:19
1 Answers
3
Converting time zones has been addressed here.
We just need fromisoformat for parsing.
The following will work with Python 3 from version 3.9 and up. If you're using Windows, make sure to run pip install tzdata
to use ZoneInfo
.
import datetime
from zoneinfo import ZoneInfo
estDatetime = datetime.datetime.fromisoformat('2020-02-02 09:30:00')
utcTimestamp = (
date
.replace(tzinfo=ZoneInfo("America/New_York"))
.astimezone(ZoneInfo('UTC'))
.timestamp()
)

Lex
- 184
- 2
- 10

Nilo Araujo
- 725
- 6
- 15
-
2also note that neither `replace` nor `astimezone` work "in-place", i.e. you need to re-assign the returned value. – FObersteiner Jul 14 '22 at 15:04
-
I'm receiving the error `zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key America/New_York'` – Lex Jul 14 '22 at 16:14
-
1@Lex are you on Windows? If so, make sure to install `tzdata`, see https://pypi.org/project/tzdata/ – FObersteiner Jul 14 '22 at 16:28
-