Python日期时间转换为具有毫秒精度的浮点数

25
在Python中,以毫秒精度存储日期和时间信息的优雅方式是什么?编辑:我正在使用Python 2.7。
我已经拼凑出了以下代码:
DT = datetime.datetime(2016,01,30,15,16,19,234000) #trailing zeros are required
DN = (DT - datetime.datetime(2000,1,1)).total_seconds()
print repr(DN)

输出:

507482179.234

然后将其恢复为日期时间格式:

DT2 = datetime.datetime(2000,1,1) + datetime.timedelta(0, DN)
print DT2

输出:

2016-01-30 15:16:19.234000

但我真的在寻找更加高雅和鲁棒的东西。

在matlab中,我会使用datenumdatetime函数:

DN = datenum(datetime(2016,01,30,15,16,19.234))

还原回去:

DT = datetime(DN,'ConvertFrom','datenum')

谢谢J.F. Sebastian,你说得对,我错过了那个问题,因为我不知道它被称为时间戳。我会研究其他的问题和答案。 - Swier
2个回答

36

Python 2:

def datetime_to_float(d):
    epoch = datetime.datetime.utcfromtimestamp(0)
    total_seconds =  (d - epoch).total_seconds()
    # total_seconds will be in decimals (millisecond precision)
    return total_seconds

def float_to_datetime(fl):
    return datetime.datetime.fromtimestamp(fl)

Python 3:

def datetime_to_float(d):
    return d.timestamp()

Python 3 版本的 float_to_datetime 与上述 Python 2 版本没有区别。


1
除非您的本地时区是UTC,否则您的Python 2/3“datetime_to_float()”版本不一致。 - jfs
datetime.datetime.fromtimestamp() 也可以用来避免时区冲突。 - Dai

15
在Python 3中,您可以使用:timestamp(以及反向的fromtimestamp)。
示例:
>>> from datetime import datetime
>>> now = datetime.now()
>>> now.timestamp()
1455188621.063099
>>> ts = now.timestamp()
>>> datetime.fromtimestamp(ts)
datetime.datetime(2016, 2, 11, 11, 3, 41, 63098)

datetime.datetime 似乎没有 timestamp 属性,这是针对 Python 3 的吗?我正在使用 2.7 版本(并且忘记提到了,抱歉)。编辑:根据 jatinderjit 的回答,看起来 .timestamp 确实只适用于 Python 3。 - Swier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接