Python 日期时间与时间戳的相互转换

标签 python datetime calendar timestamp

经过相当多的努力和阅读,我想出了以下两个函数,其中一个是(或旨在是)另一个的精确逆函数。第一个采用 Python 日期时间对象(简单)并将其转换为自纪元以来的整数秒;另一个则相反:

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/

相关文章:

c# - 如何获取一天的开始和结束时间

c# - 通过 EWS 和 C# 访问没有邮箱的资源日历

java - 如何调用其他方法的返回是其他方法的输入?

python - BOTO3:打印特定区域的实例信息

R - 使用 HHMMSS 格式将日期和时间字段转换为 POSIXct

python - matplotlib - 沿绘图线更改标记颜色

python - 如何在 MongoDB 中以 dd/mm/yyyy 形式存储和检索日期?

android - 当语言环境为阿拉伯语时,android 中的日期格式问题

具有积分函数的python拟合曲线

python - PIL协助Python