gpt4 book ai didi

Python将自纪元时间以来的一系列秒转换为日期时间系列

转载 作者:行者123 更新时间:2023-12-01 04:00:02 25 4
gpt4 key购买 nike

是否有任何快速方法可以将纪元时间以来的一系列秒转换为日期时间对象系列?

我使用:

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

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

最佳答案

您可以使用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

结论:@内特猫,如您所见,16.9 毫秒54.5 秒

关于Python将自纪元时间以来的一系列秒转换为日期时间系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36730148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com