python datetime to float with millisecond precision [duplicate]

只愿长相守 提交于 2020-12-29 09:27:23

问题


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

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 datenum and datetime functions:

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

And to revert back:

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

回答1:


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

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




回答2:


Maybe timestamp (and 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)


来源:https://stackoverflow.com/questions/35337299/python-datetime-to-float-with-millisecond-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!