时间戳转换未能产生所需的结果

时间:2016-07-07 17:56:45

标签: python-2.7 datetime pandas time

我有一个带有日期和时间列的pandas数据框等等,我试图将这两列转换为具有微秒精度的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

那么我如何包含带有时间戳的微秒?

2 个答案:

答案 0 :(得分:2)

您可以使用np.int64精度转换为ns的unix时间:

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

答案 1 :(得分:-1)

这样做=)

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