繁体   English   中英

Python将自纪元时间起的一系列秒转换为datetime系列

[英]Python convert a series of seconds since epoch time to datetime series

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

我用:

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

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

您可以使用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 ms vs. 54.5 s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM