gpt4 book ai didi

python - 将 pandas.Series 中的时间戳转换为 datetime.datetime

转载 作者:行者123 更新时间:2023-12-02 02:49:23 24 4
gpt4 key购买 nike

我有 pandas 系列,其中索引是整数(时间戳)列表,如何将它们转换为 datetime.datetime (带时区)比下面的原始转换更有效?

pd.Series(data=s.values, index=map(lambda x:datetime.datetime.fromtimestamp(x,tz=utc), s.index))

最佳答案

In [49]: s = Series(range(10))

使用to_datetime,您可以提供一个单位来选择整数的含义。

In [50]: pd.to_datetime(s,unit='s')
Out[50]:
0 1970-01-01 00:00:00
1 1970-01-01 00:00:01
2 1970-01-01 00:00:02
3 1970-01-01 00:00:03
4 1970-01-01 00:00:04
5 1970-01-01 00:00:05
6 1970-01-01 00:00:06
7 1970-01-01 00:00:07
8 1970-01-01 00:00:08
9 1970-01-01 00:00:09
dtype: datetime64[ns]

In [51]: pd.to_datetime(s,unit='ms')
Out[51]:
0 1970-01-01 00:00:00
1 1970-01-01 00:00:00.001000
2 1970-01-01 00:00:00.002000
3 1970-01-01 00:00:00.003000
4 1970-01-01 00:00:00.004000
5 1970-01-01 00:00:00.005000
6 1970-01-01 00:00:00.006000
7 1970-01-01 00:00:00.007000
8 1970-01-01 00:00:00.008000
9 1970-01-01 00:00:00.009000
dtype: datetime64[ns]

In [52]: pd.to_datetime(s,unit='D')
Out[52]:
0 1970-01-01
1 1970-01-02
2 1970-01-03
3 1970-01-04
4 1970-01-05
5 1970-01-06
6 1970-01-07
7 1970-01-08
8 1970-01-09
9 1970-01-10
dtype: datetime64[ns]

创建系列非常简单

In [54]: Series(s.values,index=pd.to_datetime(s,unit='s'))
Out[54]:
1970-01-01 00:00:00 0
1970-01-01 00:00:01 1
1970-01-01 00:00:02 2
1970-01-01 00:00:03 3
1970-01-01 00:00:04 4
1970-01-01 00:00:05 5
1970-01-01 00:00:06 6
1970-01-01 00:00:07 7
1970-01-01 00:00:08 8
1970-01-01 00:00:09 9
dtype: int64

关于python - 将 pandas.Series 中的时间戳转换为 datetime.datetime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22554339/

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