【问题标题】:Microsecond accurate timestamp in python?python中的微秒精确时间戳?
【发布时间】:2014-09-20 23:07:44
【问题描述】:

在将 Python 日期时间转换为时间戳时,有没有办法保持微秒精度?

>>> import datetime
>>> d1 = datetime.datetime(2013,7,31,9,13,8,829)
>>> import time
>>> d1_ts = time.mktime(d1.timetuple())
>>> d1
datetime.datetime(2013, 7, 31, 9, 13, 8, 829)
>>> d1_ts
1375279988.0
>>> d1.fromtimestamp(d1_ts)
datetime.datetime(2013, 7, 31, 9, 13, 8)

我在转换过程中丢失了 .829。这是相当重要的,因为我有开始和结束时间戳,我需要以设定的时间间隔(以亚秒级的步骤)逐步通过以从某些传感器收集数据。

最终会在类似这样的函数中使用:

from scipy import arange
sample_time = 0.02
for i in arange(d1_ts, d2_ts, sample_time):
    # do stuff

sample_time 这么小,微秒很重要。

【问题讨论】:

  • 如果您只想在 Windows 中的 Python 中获得毫秒或微秒分辨率的时间戳,您可以使用 QPC 时钟,它具有亚微秒的分辨率。此处演示了在 Windows 中访问此时钟的 Python 代码:stackoverflow.com/questions/38319606/…

标签: python timestamp


【解决方案1】:
import datetime as DT
d1 = DT.datetime(2013, 7, 31, 9, 13, 8, 829)
epoch = DT.datetime(1970, 1, 1)

print(d1.timestamp()) #  python3
# 1375276388.000829
print((d1 - epoch).total_seconds())  # python2
# 1375261988.000829

另外请注意,如果您使用的是 NumPy 1.7 或更高版本,您可以使用np.datetime64

In [23]: x = np.datetime64(d1)

In [24]: x.view('<i8')/1e6
Out[24]: 1375261988.000829

In [38]: x.astype('<i8').view('<M8[us]')
Out[38]: numpy.datetime64('2013-07-31T05:13:08.000829-0400')

In [40]: x.astype('<i8').view('<M8[us]') == x
Out[40]: True

由于np.datetime64 提供了一种将日期转换为8 字节ints 的简单方法,因此它们可以非常方便地像ints 那样进行算术运算,然后再转换为日期。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2011-10-18
    • 2016-02-22
    • 2017-08-11
    • 1970-01-01
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多