How to convert datetime object to milliseconds

Klausos Klausos picture Klausos Klausos · Nov 2, 2015 · Viewed 28.8k times · Source

I am parsing datetime values as follows:

df['actualDateTime'] = pd.to_datetime(df['actualDateTime'])

How can I convert this datetime objects to milliseconds?

I didn't see mention of milliseconds in the doc of to_datetime.

Update (Based on feedback): This is the current version of the code that provides error TypeError: Cannot convert input to Timestamp. The column Date3 must contain milliseconds (as a numeric equivalent of a datetime object).

import pandas as pd
import time

s1 = {'Date' : ['2015-10-20T07:21:00.000','2015-10-19T07:18:00.000','2015-10-19T07:15:00.000']}

df = pd.DataFrame(s1)

df['Date2'] = pd.to_datetime(df['Date'])

t = pd.Timestamp(df['Date2'])

df['Date3'] = time.mktime(t.timetuple())

print df

Answer

notrai picture notrai · Nov 2, 2015

You can try pd.to_datetime(df['actualDateTime'], unit='ms')

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html

says this will denote in epoch, with variations 's','ms', 'ns' ...

Update

If you want in epoch timestamp of the form 14567899..

import pandas as pd
import time
t = pd.Timestamp('2015-10-19 07:22:00')
time.mktime(t.timetuple())

>> 1445219520.0

Latest update

df = pd.DataFrame(s1)
df1 = pd.to_datetime(df['Date'])
pd.DatetimeIndex(df1)
>>>DatetimeIndex(['2015-10-20 07:21:00', '2015-10-19 07:18:00',
           '2015-10-19 07:15:00'],
          dtype='datetime64[ns]', freq=None)
df1.astype(np.int64) 
>>>0    1445325660000000000
1    1445239080000000000
2    1445238900000000000
df1.astype(np.int64) // 10**9
>>>0    1445325660
1    1445239080
2    1445238900
Name: Date, dtype: int64