将纪元时间转换为本地时间

时间:2018-10-13 06:54:47

标签: python python-3.x pandas

我有一个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)

无论如何,我是否可以对上述操作进行矢量化处理以获取所需格式的日期时间?

1 个答案:

答案 0 :(得分:1)

IIUC,我认为您需要将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用作:

((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]