我有一个 pandas 数据框,其中一列是表示为纪元时间的时间。数据框如下所示:
0 1539340322842
1 1539340426841
2 1539340438482
3 1539340485658
4 1539340495920
Name: Time, dtype: int64
我试过这个
df["local_time"] = df.epoch_time.dt.tz_localize("UTC")
但这并没有给我本地时间的结果。这是上面操作的结果:
local_time
0 1970-01-01 00:25:39.340322842+00:00
1 1970-01-01 00:25:39.340426841+00:00
2 1970-01-01 00:25:39.340438482+00:00
3 1970-01-01 00:25:39.340485658+00:00
4 1970-01-01 00:25:39.340495920+00:00
给我想要的结果的另一件事是:
def convert_time(x):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(x/1000))
df["local_time"] = df["epoch_time"].apply(convert_time)
无论如何,我可以对上述操作进行矢量化以获得我想要的格式的日期时间吗?
最佳答案
IIUC,我认为你需要 pandas to_datetime
和 units='s'
:
pd.to_datetime(df.Time/1000,unit='s')
0 2018-10-12 10:32:02.842000008
1 2018-10-12 10:33:46.841000080
2 2018-10-12 10:33:58.482000113
3 2018-10-12 10:34:45.657999992
4 2018-10-12 10:34:55.920000076
Name: Time, dtype: datetime64[ns]
或者使用astype
as:
((df.Time)/1000).astype("datetime64[s]")
0 2018-10-12 10:32:02
1 2018-10-12 10:33:46
2 2018-10-12 10:33:58
3 2018-10-12 10:34:45
4 2018-10-12 10:34:55
Name: Time, dtype: datetime64[ns]
或者
pd.to_datetime(df.Time/1000,unit='s',utc=True)
0 2018-10-12 10:32:02.842000008+00:00
1 2018-10-12 10:33:46.841000080+00:00
2 2018-10-12 10:33:58.482000113+00:00
3 2018-10-12 10:34:45.657999992+00:00
4 2018-10-12 10:34:55.920000076+00:00
Name: Time, dtype: datetime64[ns, UTC]
<小时/>
由于'Asia/Kolkata'
是05:30:00
,只需添加Timedelta
:
pd.to_datetime(df.Time/1000,unit='s')+pd.Timedelta("05:30:00")
0 2018-10-12 16:02:02.842000008
1 2018-10-12 16:03:46.841000080
2 2018-10-12 16:03:58.482000113
3 2018-10-12 16:04:45.657999992
4 2018-10-12 16:04:55.920000076
Name: Time, dtype: datetime64[ns]
关于python - 将纪元时间转换为本地时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52790340/