Search code examples
pythonpython-3.xpandasdataframeepoch

How to convert a column in df having epoch with date time format and vice-versa?


1.have df with values

    0            1 
0 sun       | 1549628346168
1 goal      | 1532230566808
2 micheal   | 1533647352218

output should be in the format of

    0            1 
0 sun       | 2019-02-02 Sat 21:16:20
1 goal      | 2019-02-02 Sat 21:16:20
2 micheal   | 2019-02-02 Sat 21:16:20

tried this how to get day in words

s = time/1000
datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S')

2.

have df with values how to concat these two and get a column with epoch time

    Date           Time 
0  08-09-2017 |  05:00 PM
1  16-06-17   |  10:27 AM
2   04-07-17  |  03:11 PM

output

    time
 1549628346168
 1532230566808
 1533647352218

Solution

  • Use to_datetime with unit='ms' first and then Series.dt.strftime with add %a for days, check also http://strftime.org/:

    df[1] = pd.to_datetime(df[1], unit='ms').dt.strftime('%Y-%m-%d %a %H:%M:%S')
    
    print (df)
             0                        1
    0      sun  2019-02-08 Fri 12:19:06
    1     goal  2018-07-22 Sun 03:36:06
    2  micheal  2018-08-07 Tue 13:09:12
    

    EDIT:

    df['dt'] = pd.to_datetime(df['Date'] + ' ' + df['Time']).astype(np.int64) // 10**9
    print (df)
             Date      Time          dt
    0  08-09-2017  05:00 PM  1502298000
    1    16-06-17  10:27 AM  1497608820
    2    04-07-17  03:11 PM  1491577860