Home > Software engineering >  Python Datetime Timezone Shift
Python Datetime Timezone Shift

Time:11-06

I have a time string disseminated from a MQTT broker that I would like to read and convert from its native timezone (U.S. Central Time) to Coordinated Universal Time (UTC). I am currently using Python 3.8.5 in Ubuntu 20.04 Focal Fossa, with the machine timezone set to UTC.

The time string is as follows: 1636039288.815212

To work with this time in Python, I am using a combination of the datetime and pytz libraries. My current core of code is as follows:

from datetime import datetime, timedelta
import pytz

input = 1636039288.815212
srctime = datetime.fromtimestamp(input, tz=pytz.timezone('US/Central'))

After running this chunk, I receive the following undesired time output:

datetime.datetime(2021, 11, 4, 10, 21, 28, 815212, tzinfo=<DstTzInfo 'US/Central' CDT-1 day, 19:00:00 DST>)

It appears that despite explicitly defining 'US/Central' inside the initial timestamp conversion, 5 hours were subsequently subtracted the initial time provided.

What additional steps/alterations can I make to ensure that the initial time provided is unchanged, defined as US/Central, and that I can subsequently change to UTC?

CodePudding user response:

Python's fromtimestamp assumes that your input is UNIX time, which should refer to 1970-01-01 UTC, not some arbitrary time zone. If you encounter such a thing nevertheless, you'll need to set UTC and then replace the tzinfo:

from datetime import datetime
from dateutil import tz # pip install python-dateutil

ts = 1636039288.815212

dt = datetime.fromtimestamp(ts, tz=tz.UTC).replace(tzinfo=tz.gettz("US/Central"))

print(dt)
# 2021-11-04 16:21:28.815212-05:00

# or in UTC:
print(dt.astimezone(tz.UTC))
# 2021-11-04 20:21:28.815212 00:00

Note that I'm using dateutil here so that the replace operation is safe. Don't do that with pytz (you must use localize there). Once you upgrade to Python 3.9, use zoneinfo instead, so you only need the standard library.

  • Related