我有一个带有日期和时间列的熊猫数据帧,我正在尝试以微秒精度将这两列转换为Unix时间戳,这样我就可以将数据帧转储到numpy内存映射文件中(这需要浮点数,或者至少不需要日期对象,所以它是必不可少的)。
因此,如果没有数据框,仅使用字符串,我得到以下内容:
DT = '2014-10-01 00:00:07.082000'
UX= time.mktime(datetime.datetime.strptime(DT, '%Y-%m-%d %H:%M:%S.%f').timetuple())
print UX
>>> 1412118007.0
tm = datetime.datetime.fromtimestamp(UX)
print tm
>>>2014-10-01 00:00:07
那么如何在时间戳中包含微秒呢?
您可以以ns
精度转换为 unix 时间的np.int64
:
df = pd.DataFrame({'A':['2014-10-01 00:00:07.082000', '2014-10-01 00:00:07.082000']})
print (df)
A
0 2014-10-01 00:00:07.082000
1 2014-10-01 00:00:07.082000
df['A'] = pd.to_datetime(df.A)
df['B'] = df.A.astype(np.int64)
df['C'] = pd.to_datetime(df.B, unit='ns')
print (df)
A B C
0 2014-10-01 00:00:07.082 1412121607082000000 2014-10-01 00:00:07.082
1 2014-10-01 00:00:07.082 1412121607082000000 2014-10-01 00:00:07.082
对于ms
精度使用:
df['B'] = (df.A.astype(np.int64) // 10**6)
df['C'] = pd.to_datetime(df.B, unit='ms')
print (df)
A B C
0 2014-10-01 00:00:07.082 1412121607082 2014-10-01 00:00:07.082
1 2014-10-01 00:00:07.082 1412121607082 2014-10-01 00:00:07.082
这样做=)
from datetime import datetime
DT = '2014-10-01 00:00:07.082000'
UX = datetime.strptime(DT, '%Y-%m-%d %H:%M:%S.%f')
print UX
>>> 2014-10-01 00:00:07.082000