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

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

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

t.toordinal()

如何将datetime对象转换为秒?


当前回答

在python 3中,以毫秒为单位计算一个代码块的处理时间的标准方法。X表示:

import datetime

t_start = datetime.datetime.now()

# Here is the python3 code, you want 
# to check the processing time of

t_end = datetime.datetime.now()
print("Time taken : ", (t_end - t_start).total_seconds()*1000, " ms")

其他回答

将表示UTC时间的datetime对象转换为POSIX时间戳:

from datetime import timezone

seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()

将表示本地时区时间的datetime对象转换为POSIX时间戳:

import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()

参见如何在Python中将本地时间转换为UTC ?如果tz数据库在给定平台上可用;只使用stdlib的解决方案可能有效。

如果需要<3.3 Python版本的解决方案,请参考链接。

来自python文档:

timedelta.total_seconds()

返回持续时间中包含的总秒数。相当于

(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

启用真除法时计算。

注意,对于非常大的时间间隔(在大多数平台上超过270年),这种方法将失去微秒精度。

此功能是2.7版中的新功能。

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())一样。

import datetime
import math


def getSeconds(inputDate):
    time = datetime.date.today().strftime('%m/%d/%Y')
    date_time = datetime.datetime.strptime(time, '%m/%d/%Y')
    msg = inputDate
    props = msg.split(".")
    a_timedelta = datetime.timedelta
    if(len(props)==3):
        a_timedelta = date_time - datetime.datetime(int(props[0]),int(props[1]),int(props[2]))
    else:
        print("Invalid date format")
        return
    seconds = math.trunc(a_timedelta.total_seconds())
    print(seconds)
    return seconds

例子getSeconds(“2022.1.1”)