【问题标题】:Python convert a series of seconds since epoch time to datetime seriesPython将自纪元时间以来的一系列秒数转换为日期时间序列
【发布时间】:2016-08-12 07:49:23
【问题描述】:

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

我用:

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

但它非常慢,因为我的数据框非常大。有什么快速的方法可以做到这一点吗?喜欢熊猫功能吗?

【问题讨论】:

  • datetime.fromtimestamp() 本质上是用 C 实现的,如果你想在 datetime 对象中得到它,它的速度差不多。
  • @Natecat,如果这么简单,那么没有人会使用 pandas ;)

标签: python datetime pandas time dataframe


【解决方案1】:

你可以使用to_datetime(..., unit='s'):

df['datetime'] = pd.to_datetime(df['epochtime'], 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

结论: @Natecat, 如您所见16.9 ms54.5 s

【讨论】:

  • 谢谢!!!这正是我正在寻找的,比循环快得多!
  • @user5025141,总是乐于提供帮助。请考虑accepting 最有帮助的答案 - 这也表明您的问题已得到解答
猜你喜欢
  • 2013-11-02
  • 2011-08-31
  • 2016-06-08
  • 2020-05-20
  • 2011-10-23
  • 2020-09-14
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多