考虑到夏令时,将 EST 时间戳转换为 GMT

Convert EST timestamp to GMT taking into account Daylight Savings

我有一个时间戳,表示自 1970 年以来的毫秒数 1432202088224,转换为 Thursday, May 21, 2015 5:54:48 AM EDT。我想编写一个 python 函数,将该时间戳转换为格林威治标准时间的毫秒数。我不能天真地将四个小时(3600000 毫秒)添加到现有时间戳,因为半年我将关闭一个小时。

我试过使用 datetimepytz

编写一个函数
def convert_mills_GMT(milliseconds):
    converted_raw = datetime.datetime.fromtimestamp(milliseconds/1000.0)
    date_eastern = eastern.localize(converted_raw, is_dst=True)
    date_utc = date_eastern.astimezone(utc)
    return int(date_utc.strftime("%s")) * 1000

使用 1432202088224 这个函数的输入 returns 1432220088000Thursday, May 21, 2015 10:54:48 AM EDT 而我想要的是 9:54 AM。我错过了什么?

Don't use .strftime("%s"). It is not supported, and may silently fail. Instead, to convert a UTC datetime to a timestamp use one of the methods shown here 取决于您的 Python 版本:

Python 3.3+:

timestamp = dt.timestamp()

Python3 (< 3.3):

epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
timestamp = (dt - epoch) / timedelta(seconds=1)

Python 2.7+:

timestamp = (dt.replace(tzinfo=None) - datetime(1970, 1, 1)).total_seconds()

Python2 (< 2.7):

def totimestamp(dt, epoch=datetime(1970,1,1)):
    td = dt - epoch
    # return td.total_seconds()
    return (td.microseconds + (td.seconds + td.days * 86400) * 10**6) / 10**6 
timestamp = totimestamp(dt.replace(tzinfo=None))

因此,您的 convert_mills_GMT 应该看起来像

def convert_mills_GMT(milliseconds, 
                      utc=pytz.utc,
                      eastern=pytz.timezone('US/Eastern')
):
    converted_raw = DT.datetime.fromtimestamp(milliseconds/1000.0)
    date_eastern = eastern.localize(converted_raw, is_dst=True)
    date_utc = date_eastern.astimezone(utc)
    timestamp = ...
    return int(timestamp) * 1000

例如,Python2.7,

import datetime as DT
import pytz

def convert_mills_GMT(milliseconds, 
                      utc=pytz.utc,
                      eastern=pytz.timezone('US/Eastern')
):
    converted_raw = DT.datetime.fromtimestamp(milliseconds/1000.0)
    date_eastern = eastern.localize(converted_raw, is_dst=True)
    date_utc = date_eastern.astimezone(utc)
    timestamp = ((date_utc.replace(tzinfo=None) - DT.datetime(1970, 1, 1))
                 .total_seconds())
    return int(timestamp) * 1000

print(DT.datetime.utcfromtimestamp(convert_mills_GMT(1432202088224)/1000.0))

打印

2015-05-21 09:54:48

没有"EST timestamp"这样的东西。如果你需要 "GMT timestamp" 那么你已经拥有了。

要从以毫秒数给出的 POSIX 时间戳获取 UTC 时间:

>>> from datetime import datetime, timedelta
>>> timestamp = 1432202088224
>>> utc_time = datetime(1970, 1, 1) + timedelta(milliseconds=timestamp)
>>> utc_time.strftime('%A, %B %d, %Y %H:%M:%S %p UTC')
'Thursday, May 21, 2015 09:54:48 AM UTC'

我们可以通过将 UTC 时间转换回 "EST" 时区来检查结果是否正确:

>>> import pytz # $ pip install pytz
>>> est = utc_time.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('US/Eastern'))
>>> est.strftime('%A, %B %d, %Y %H:%M:%S %p %Z')
'Thursday, May 21, 2015 05:54:48 AM EDT'