python datetime以毫秒精度浮动 [英] python datetime to float with millisecond precision
本文介绍了python datetime以毫秒精度浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用毫秒精度在python浮点数中存储日期和时间信息的经典方法是什么?我正在使用python 2.7
What is a classy way to store date and time information in a float in python with millisecond precision? I'm using python 2.7
我一起破解了以下内容:
I've hacked together the following:
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
但是我真的在寻找一些更经典,更坚固的东西.
But I'm really looking for something a little more classy and robust.
在matlab中,我将使用 datenum
和 datetime
函数:
In matlab I would use the datenum
and datetime
functions:
DN = datenum(datetime(2016,01,30,15,16,19.234))
并返回:
DT = datetime(DN,'ConvertFrom','datenum')
推荐答案
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:
Python 3:
def datetime_to_float(d):
return d.timestamp()
float_to_datetime
的python 3版本与上面的python 2版本没有什么不同.
The python 3 version of float_to_datetime
will be no different from the python 2 version above.
这篇关于python datetime以毫秒精度浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文