Lex
Lex

Reputation: 184

Convert EST Datetime to UTC Timestamp in Python 3

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.

Upvotes: 0

Views: 3794

Answers (1)

Nilo Araujo
Nilo Araujo

Reputation: 815

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()
)

Upvotes: 3

Related Questions