Localizing Epoch Time with pytz in Python

眉间皱痕 提交于 2019-11-30 02:01:19

datetime.fromtimestamp(self.epoch) returns localtime that shouldn't be used with an arbitrary timezone.localize(); you need utcfromtimestamp() to get datetime in UTC and then convert it to a desired timezone:

from datetime import datetime
import pytz

# get time in UTC
utc_dt = datetime.utcfromtimestamp(posix_timestamp).replace(tzinfo=pytz.utc)

# convert it to tz
tz = pytz.timezone('America/New_York')
dt = utc_dt.astimezone(tz)

# print it
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Or a simpler alternative is to construct from the timestamp directly:

from datetime import datetime
import pytz

# get time in tz
tz = pytz.timezone('America/New_York')
dt = datetime.fromtimestamp(posix_timestamp, tz)
# print it
print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

It converts from UTC implicitly in this case.

For creating the datetime object belonging to particular timezone from a unix timestamp, you may pass the pytz object as a tz parameter while creating your datetime. For example:

>>> from datetime import datetime
>>> import pytz

>>> datetime.fromtimestamp(1350663248, tz= pytz.timezone('America/New_York'))
datetime.datetime(2012, 10, 19, 12, 14, 8, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)

You can get the list of all timezones using pytz.all_timezones which returns exhaustive list of the timezone names that can be used.

Also take a look at List of tz database time zones wiki.

epochdt = datetime.datetime.fromtimestamp(epoch)
timezone1 = timezone("Timezone/String")
adjusted_datetime = timezone1.localize(epochdt)

Working from memory, so excuse any syntax errors, but that should get you on the right track.

EDIT: Missed the part about knowing the hour,etc. Python has great Time/Date Formatting. At pretty much the bottom of that link is the table showing how to pull different attributes from the datetime object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!