python datetime以毫秒精度浮动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35337299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:19:06  来源:igfitidea点击:

python datetime to float with millisecond precision

pythonpython-2.7datetime

提问by Swier

What is a classy way to store date and time information in a float in python with millisecond precision? Edit: I'm using python 2.7

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

Output:

输出:

507482179.234

And then to revert back to datetime:

然后恢复到日期时间:

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

Output:

输出:

2016-01-30 15:16:19.234000

But I'm really looking for something a little more classy and robust.

但我真的在寻找更优雅和更强大的东西。

In matlab I would use the datenumand datetimefunctions:

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

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

And to revert back:

并恢复:

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

采纳答案by jatinderjit

Python 2:

蟒蛇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:

蟒蛇3:

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

The python 3 version of float_to_datetimewill be no different from the python 2 version above.

python 3 版本float_to_datetime将与上面的 python 2 版本没有区别。

回答by second

Maybe timestamp(and fromtimestamp)

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