gpt4 book ai didi

Python 日期时间到时间戳的转换和返回

转载 作者:太空宇宙 更新时间:2023-11-04 01:16:10 26 4
gpt4 key购买 nike

经过相当大的努力和阅读,我想出了以下两个函数,其中一个是(或打算是)另一个的完全反函数。第一个采用 Python datetime 对象(天真)并将其转换为自纪元以来的整数秒数;另一个则相反:

import datetime
import time
import calendar

def datetime2timestamp(dt):
''' Accepts a naive datetime object and converts it to a time in seconds since the start of 1970'''
return(calendar.timegm(dt.timetuple()))

def timestamp2datetime(ts):
''' Accepts a time in seconds since the start of 1970 and converts it to a naive datetime object'''
return(datetime.datetime.fromtimestamp(time.mktime(time.gmtime(ts))))

>>> dt = datetime.datetime(1970, 1, 1, 0, 0, 1)
>>> print dt
1970-01-01 00:00:01
>>> ts = datetime2timestamp(dt)
>>> print ts
1
>>> dt = timestamp2datetime(ts)
>>> print dt
1970-01-01 00:00:01

两个问题:

1) 有没有一种方法可以更简单地完成同一件事(尤其是第二个功能)而不需要导入三个不同的模块?我之前发现的更简单的解决方案存在缺陷,即它们在我的计算机上的本地时间与 UTC 之间的区别不一致。

2) 有没有办法让时间戳成为 float 而不是 calendar.timegm() 返回的整数秒数?

最佳答案

1) Is there a way to accomplish the same thing (especially the second function) more simply and without requiring the importing of three different modules? Simpler solutions I had previously found had the defect that they were inconsistent about the distinction between the local time on my computer and UTC.

2) Is there a way to have the timestamp be a float instead of the integer number of seconds returned by calendar.timegm() ?

calendar.timegm() 仅适用于 UTC 时间。返回 float 的更简单版本是:

seconds_since_epoch = (dt - datetime(1970, 1, 1)).total_seconds()

如果 dt 是本地时间(在这种情况下您可以使用 time.mktime() + dt.microsecond/1e6),两者都不起作用。记住, 本地时间可能不明确或不存在(例如,由于 DST 转换)。不要忘记,如果您使用 float ,您可能会失去精度。

转换回来:

dt = datetime(1970, 1, 1) + timedelta(seconds=seconds_since_epoch)

结果是 dt——一个表示 UTC 时区时间的原始日期时间对象。

如果你想获得本地时间,那么你可以使用:

local_dt = datetime.fromtimestamp(seconds_since_epoch)

如果 time.gmtime(0)1970-01-01,则后者和 time.mktime() 可以正常工作(接受/返回 POSIX 时间戳) 00:00:00+00:00(POSIX 纪元)。

关于Python 日期时间到时间戳的转换和返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24542668/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com