Microsecond accurate timestamp in python?
在将Python日期时间转换为时间戳时,有没有办法保持微秒精度?
1 2 3 4 5 6 7 8 9 10 | >>> 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) |
我在转换时失去了
最终它将用于类似于此的函数:
1 2 3 4 | from scipy import arange sample_time = 0.02 for i in arange(d1_ts, d2_ts, sample_time): # do stuff |
如果
1 2 3 4 5 6 7 8 | 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:
1 2 3 4 5 6 7 8 9 10 | 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 |
由于