Python将从历元时间开始的一系列秒转换为日期时间序列

Python将从历元时间开始的一系列秒转换为日期时间序列,python,datetime,pandas,time,dataframe,Python,Datetime,Pandas,Time,Dataframe,有没有什么快速的方法可以将历元时间后的一系列秒转换为日期时间对象系列 我使用: for i in range(len(df)): df['datetime'].iloc[i] = datetime.fromtimestamp(df['epochtime'].iloc[i]) 但是它非常慢,因为我的数据帧非常大。有什么快速的方法可以做到这一点吗?像pandas函数一样?您可以使用来确定日期时间(…,unit='s'): 时间比较: In [158]: df = pd.DataFrame(

有没有什么快速的方法可以将历元时间后的一系列秒转换为日期时间对象系列

我使用:

for i in range(len(df)):
    df['datetime'].iloc[i] = datetime.fromtimestamp(df['epochtime'].iloc[i])

但是它非常慢,因为我的数据帧非常大。有什么快速的方法可以做到这一点吗?像pandas函数一样?

您可以使用
来确定日期时间(…,unit='s')

时间比较:

In [158]: df = pd.DataFrame({'epochtime': pd.date_range('2001-01-01', freq='1S', periods=10**5)}).astype(np.int64)//10**9

In [159]:

In [159]: df.head()
Out[159]:
   epochtime
0  978307200
1  978307201
2  978307202
3  978307203
4  978307204

In [160]:

In [160]: len(df)
Out[160]: 100000

In [161]:

In [161]: %timeit df['datetime'] = pd.to_datetime(df['epochtime'], unit='s')
100 loops, best of 3: 16.9 ms per loop

In [162]:

In [162]: %%timeit
   .....: for i in range(len(df)):
   .....:     df['datetime'].iloc[i] = datetime.fromtimestamp(df2['epochtime'].iloc[i])
   .....:
c:\envs\py35\lib\site-packages\pandas\core\indexing.py:128: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
1 loop, best of 3: 54.5 s per loop
结论: @自然科学,
正如您所看到的,
16.9毫秒
vs.
54.5秒

日期时间。fromtimestamp()基本上是用C实现的,如果您想在datetime对象中使用它,它的速度是最快的。@Natecat,如果它这么简单,那么就没有人会使用pandas;)谢谢这正是我想要的,比循环快得多@用户5025141,总是乐于帮助。请考虑最有用的答案——这也表明你的问题已经得到解答。
In [158]: df = pd.DataFrame({'epochtime': pd.date_range('2001-01-01', freq='1S', periods=10**5)}).astype(np.int64)//10**9

In [159]:

In [159]: df.head()
Out[159]:
   epochtime
0  978307200
1  978307201
2  978307202
3  978307203
4  978307204

In [160]:

In [160]: len(df)
Out[160]: 100000

In [161]:

In [161]: %timeit df['datetime'] = pd.to_datetime(df['epochtime'], unit='s')
100 loops, best of 3: 16.9 ms per loop

In [162]:

In [162]: %%timeit
   .....: for i in range(len(df)):
   .....:     df['datetime'].iloc[i] = datetime.fromtimestamp(df2['epochtime'].iloc[i])
   .....:
c:\envs\py35\lib\site-packages\pandas\core\indexing.py:128: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)
1 loop, best of 3: 54.5 s per loop