在Python中使用pytz本地化时代时间 [英] Localizing Epoch Time with pytz in Python
问题描述
我正在使用pytz将纪元时间戳转换为不同时区中的日期。我正在尝试做的是创建一个DateTime对象,该对象接受Olson数据库时区和一个纪元时间并返回本地化的datetime对象。最终,我需要回答诸如在新纪元1350663248的纽约几点钟了?之类的问题。
Im working on converting epoch timestamps to dates in different timezones with pytz. What I am trying to do is create a DateTime object that accepts an Olson database timezone and an epoch time and returns a localized datetime object. Eventually I need to answer questions like "What hour was it in New York at epoch time 1350663248?"
此处某些内容无法正常工作:
Something is not working correctly here:
import datetime, pytz, time
class DateTime:
def __init__(self, timezone, epoch):
self.timezone = timezone
self.epoch = epoch
timezoneobject = pytz.timezone(timezone)
datetimeobject = datetime.datetime.fromtimestamp( self.epoch )
self.datetime = timezoneobject.localize(datetimeobject)
def hour(self):
return self.datetime.hour
if __name__=='__main__':
epoch = time.time()
dt = DateTime('America/Los_Angeles',epoch)
print dt.datetime.hour
dt = DateTime('America/New_York',epoch)
print dt.datetime.hour
此命令打印同一小时,而提前3个小时左右。怎么了我是Python的新手,非常感谢!
This prints the same hour, whereas one should be 3 or so hours ahead. Whats going wrong here? I'm a total Python beginner, any help is appreciated!
推荐答案
datetime.fromtimestamp(self。
返回不应与任意时区一起使用的本地时间。您需要 utcfromtimestamp()
来获取UTC中的日期时间,然后将其转换为所需的时区:
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'))
在这种情况下,它是从UTC隐式转换的。
It converts from UTC implicitly in this case.
这篇关于在Python中使用pytz本地化时代时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!