python datetime以毫秒精度浮动

python datetime to float with millisecond precision

本问题已经有最佳答案,请猛点这里访问。

什么是在python中以毫秒精度在float中存储日期和时间信息的优雅方法?
编辑:我正在使用python 2.7

我一起攻击了以下内容:

1
2
3
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)

输出:

1
507482179.234

然后恢复到日期时间:

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

输出:

1
2016-01-30 15:16:19.234000

但我真的在寻找一些更优雅,更健壮的东西。

在matlab中我会使用datenumdatetime函数:

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

并回复:

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


Python 2:

1
2
3
4
5
6
7
8
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:

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

float_to_datetime将是相同的。


也许timestamp(和fromtimestamp)

1
2
3
4
5
6
7
>>> 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)