Python pandas convert datetime to timestamp effectively through dt accessor Python pandas convert datetime to timestamp effectively through dt accessor python python

Python pandas convert datetime to timestamp effectively through dt accessor


I think you need convert first to numpy array by values and cast to int64 - output is in ns, so need divide by 10 ** 9:

df['ts'] = df.datetime.values.astype(np.int64) // 10 ** 9print (df)              datetime          ts0  2016-01-01 00:00:01  14516064011  2016-01-01 01:00:01  14516100012  2016-01-01 02:00:01  14516136013  2016-01-01 03:00:01  14516172014  2016-01-01 04:00:01  14516208015  2016-01-01 05:00:01  14516244016  2016-01-01 06:00:01  14516280017  2016-01-01 07:00:01  14516316018  2016-01-01 08:00:01  14516352019  2016-01-01 09:00:01  145163880110 2016-01-01 10:00:01  145164240111 2016-01-01 11:00:01  145164600112 2016-01-01 12:00:01  145164960113 2016-01-01 13:00:01  145165320114 2016-01-01 14:00:01  145165680115 2016-01-01 15:00:01  145166040116 2016-01-01 16:00:01  145166400117 2016-01-01 17:00:01  145166760118 2016-01-01 18:00:01  145167120119 2016-01-01 19:00:01  145167480120 2016-01-01 20:00:01  145167840121 2016-01-01 21:00:01  145168200122 2016-01-01 22:00:01  145168560123 2016-01-01 23:00:01  145168920124 2016-01-02 00:00:01  1451692801

to_timestamp is used for converting from period to datetime index.


I think you should not use apply, simply astype would be fine:

df['ts'] = df.datetime.astype('int64') // 10**9


There's also another method to do this using the "hidden" attribute of DatetimeIndex called asi8, which creates an integer timestamp.

pd.DatetimeIndex(df.datetime).asi8

Wes McKinney suggested it in this tangentially related stackoverflow question linked here