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

时间:2015-05-22 18:08:11

标签: python timezone pytz

我有一个时间戳,表示自1970年以来的毫秒1432202088224,转换为Thursday, May 21, 2015 5:54:48 AM EDT。我想编写一个python函数,将GMT中的时间戳转换为毫秒。我不能天真地将四小时(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的输入,当我想要的是9:54 AM时,此函数返回1432220088000 Thursday, May 21, 2015 10:54:48 AM EDT。我错过了什么?

2 个答案:

答案 0 :(得分:2)

没有“EST时间戳”这样的东西。如果您需要“GMT时间戳”,那么您已经拥有它。

从以毫秒数给出的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'

答案 1 :(得分:0)

Don't use .strftime("%s"). It is not supported, and may silently fail.相反,要将UTC日期时间转换为时间戳,请使用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