我有一堆datetime对象,我想为每个对象计算从过去的固定时间(例如从1970年1月1日以来)开始的秒数。

import datetime
t = datetime.datetime(2009, 10, 21, 0, 0)

这似乎只是区分有不同日期的日期:

t.toordinal()

如何将datetime对象转换为秒?


当前回答

我试了试标准图书馆的日历。Timegm,它工作得很好:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

裁判:https://docs.python.org/2/library/calendar.html # calendar.timegm

其他回答

我试了试标准图书馆的日历。Timegm,它工作得很好:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

裁判:https://docs.python.org/2/library/calendar.html # calendar.timegm

从Python 3.3开始,使用datetime.timestamp()方法,这变得超级简单。当然,这只在您需要1970-01-01 UTC的秒数时才有用。

from datetime import datetime
dt = datetime.today()  # Get timezone naive now
seconds = dt.timestamp()

返回值将是一个浮点数,表示秒的几分之一。如果datetime是无时区的(如上例所示),则假定datetime对象表示本地时间,即从您所在位置的当前时间到UTC 1970-01-01的秒数。

Python提供了datetime操作来计算两个日期之间的差值。在你的情况下,这将是:

t - datetime.datetime(1970,1,1)

返回的值是一个timedelta对象,您可以使用成员函数total_seconds获取以秒为单位的值。

(t - datetime.datetime(1970,1,1)).total_seconds()

我并没有在所有的答案中看到这一点,尽管我猜这是默认的需求:

t_start = datetime.now()
sleep(2)
t_end = datetime.now()
duration = t_end - t_start
print(round(duration.total_seconds()))

如果不使用.total_seconds(),则抛出:TypeError: type datetime。Timedelta没有定义__round__方法。

例子:

>>> duration
datetime.timedelta(seconds=53, microseconds=621861)
>>> round(duration.total_seconds())
54
>>> duration.seconds
53

持续时间。Seconds只使用秒,不考虑微秒,就像运行math.floor(duration.total_seconds())一样。

Int (t.strftime("%s"))也可以