我正在处理Python中的日期,我需要将它们转换为UTC时间戳以供使用 在Javascript。下面的代码不能工作:

>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datetime(2010, 12, 31, 23, 0)

首先将date对象转换为datetime也没有帮助。我在这个链接中尝试了这个例子,但是:

from pytz import utc, timezone
from datetime import datetime
from time import mktime
input_date = datetime(year=2011, month=1, day=15)

现在:

mktime(utc.localize(input_date).utctimetuple())

or

mktime(timezone('US/Eastern').localize(input_date).utctimetuple())

做的工作。

一般问题:如何根据UTC将日期转换为从epoch开始的秒数?


当前回答

Assumption 1: You're attempting to convert a date to a timestamp, however since a date covers a 24 hour period, there isn't a single timestamp that represents that date. I'll assume that you want to represent the timestamp of that date at midnight (00:00:00.000). Assumption 2: The date you present is not associated with a particular time zone, however you want to determine the offset from a particular time zone (UTC). Without knowing the time zone the date is in, it isn't possible to calculate a timestamp for a specific time zone. I'll assume that you want to treat the date as if it is in the local system time zone.

首先,您可以使用timetuple()成员将日期实例转换为表示各种时间组件的元组:

dtt = d.timetuple() # time.struct_time(tm_year=2011, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)

然后你可以使用time.mktime将其转换为时间戳:

ts = time.mktime(dtt) # 1293868800.0

您可以通过使用epoch时间本身(1970-01-01)测试来验证此方法,在这种情况下,函数应该返回该日期本地时区的时区偏移量:

d = datetime.date(1970,1,1)
dtt = d.timetuple() # time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
ts = time.mktime(dtt) # 28800.0

28800.0是8小时,这对太平洋时区(我所在的时区)来说是正确的。

其他回答

使用箭头包:

>>> import arrow
>>> arrow.get(2010, 12, 31).timestamp
1293753600
>>> time.gmtime(1293753600)
time.struct_time(tm_year=2010, tm_mon=12, tm_mday=31, 
    tm_hour=0, tm_min=0, tm_sec=0, 
    tm_wday=4, tm_yday=365, tm_isdst=0)

这个问题有点混乱。时间戳不是UTC -它们是Unix的东西。日期可能是UTC?假设它是,并且如果你使用的是Python 3.2+,那么simple-date使这个问题变得微不足道:

>>> SimpleDate(date(2011,1,1), tz='utc').timestamp
1293840000.0

如果你有年、月和日,你不需要创建日期:

>>> SimpleDate(2011,1,1, tz='utc').timestamp
1293840000.0

如果日期在其他时区(这很重要,因为我们假设是午夜,没有相关的时间):

>>> SimpleDate(date(2011,1,1), tz='America/New_York').timestamp
1293858000.0

[simple-date背后的想法是将所有python的日期和时间收集到一个一致的类中,这样你就可以进行任何转换。例如,它也会向另一个方向发展:

>>> SimpleDate(1293858000, tz='utc').date
datetime.date(2011, 1, 1)

]

我定义了自己的两个函数

,已知的utc_time2datetime (utc_time表示tz =没有) datetime2utc_time (datetime)

在这里:

import time
import datetime
from pytz import timezone
import calendar
import pytz


def utc_time2datetime(utc_time, tz=None):
    # convert utc time to utc datetime
    utc_datetime = datetime.datetime.fromtimestamp(utc_time)

    # add time zone to utc datetime
    if tz is None:
        tz_datetime = utc_datetime.astimezone(timezone('utc'))
    else:
        tz_datetime = utc_datetime.astimezone(tz)

    return tz_datetime


def datetime2utc_time(datetime):
    # add utc time zone if no time zone is set
    if datetime.tzinfo is None:
        datetime = datetime.replace(tzinfo=timezone('utc'))

    # convert to utc time zone from whatever time zone the datetime is set to
    utc_datetime = datetime.astimezone(timezone('utc')).replace(tzinfo=None)

    # create a time tuple from datetime
    utc_timetuple = utc_datetime.timetuple()

    # create a time element from the tuple an add microseconds
    utc_time = calendar.timegm(utc_timetuple) + datetime.microsecond / 1E6

    return utc_time

一个完整的时间字符串包含:

日期 时间 utcoffset [+HHMM或-HHMM]

例如:

0000 == UNIX时间戳:3600

$ python3
>>> from datetime import datetime
>>> from calendar import timegm
>>> tm = '1970-01-01 06:00:00 +0500'
>>> fmt = '%Y-%m-%d %H:%M:%S %z'
>>> timegm(datetime.strptime(tm, fmt).utctimetuple())
3600

注意:

UNIX时间戳是一个浮点数,以UTC标准从epoch开始的秒数表示。


编辑:

$ python3
>>> from datetime import datetime, timezone, timedelta
>>> from calendar import timegm
>>> dt = datetime(1970, 1, 1, 6, 0)
>>> tz = timezone(timedelta(hours=5))
>>> timegm(dt.replace(tzinfo=tz).utctimetuple())
3600

考虑到您有一个名为d的datetime对象, 使用以下方法获得UTC时间戳:

d.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

而对于相反的方向,使用以下方法:

d = datetime.strptime("2008-09-03T20:56:35.450686Z", "%Y-%m-%dT%H:%M:%S.%fZ")