python datetime以毫秒精度浮动

时间:2016-02-11 10:51:38

标签: python datetime

在python中以毫秒精度在float中存储日期和时间信息的经典方法是什么? 编辑:我使用的是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')

2 个答案:

答案 0 :(得分:11)

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()

float_to_datetime将是相同的。

答案 1 :(得分:2)

也许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)

gcc test.c -L . -lasntc -ltc -lresolv -lnetlink -lutil -ltc -lm -o mytc
 nm mytc | grep htb_qdisc_util
                 w htb_qdisc_util