enterML
enterML

Reputation: 2285

Converting epoch time to localtime

I have a pandas dataframe and one of the columns is time represented as the epoch time. The dataframe looks like this:

0    1539340322842
1    1539340426841
2    1539340438482
3    1539340485658
4    1539340495920
Name: Time, dtype: int64

I tried this df["local_time"] = df.epoch_time.dt.tz_localize("UTC") but this doesn't give me the result in local time. This is the result of the above operation:

                        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  

The other thing that gave me the result I want is this:

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)

Is there anyway that I can vectorize the above operation to get the datetime in the format I want?

Upvotes: 1

Views: 246

Answers (1)

Space Impact
Space Impact

Reputation: 13255

IIUC, I think you need pandas to_datetime with 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]

Or using 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]

Or

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]

Since 'Asia/Kolkata' is 05:30:00 ahead just add 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]

Upvotes: 1

Related Questions