Swi*_*ier 7 python datetime python-2.7
什么是在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)
Run Code Online (Sandbox Code Playgroud)
输出:
507482179.234
Run Code Online (Sandbox Code Playgroud)
然后恢复到日期时间:
DT2 = datetime.datetime(2000,1,1) + datetime.timedelta(0, DN)
print DT2
Run Code Online (Sandbox Code Playgroud)
输出:
2016-01-30 15:16:19.234000
Run Code Online (Sandbox Code Playgroud)
但我真的在寻找一些更优雅,更健壮的东西.
在matlab中我会使用datenum
和datetime
函数:
DN = datenum(datetime(2016,01,30,15,16,19.234))
Run Code Online (Sandbox Code Playgroud)
并回复:
DT = datetime(DN,'ConvertFrom','datenum')
Run Code Online (Sandbox Code Playgroud)
jat*_*jit 14
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)
Run Code Online (Sandbox Code Playgroud)
Python 3:
def datetime_to_float(d):
return d.timestamp()
Run Code Online (Sandbox Code Playgroud)
float_to_datetime
会是一样的.
在Python 3,你可以使用: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)
Run Code Online (Sandbox Code Playgroud)