1

In python 3.6.0 and pandas 0.20.0

there is a date column yyyy-mm-dd

date
2017-08-16
2017-08-17
2017-08-18

There is the same question here

Convert a column of datetimes to epoch in Python

But sadly none of the solutions in the post works

df['date']=df['date'].astype('int64')//1e9

ValueError: invalid literal for int() with base 10: '2017-08-16'


df['date']=(df['date'] - dt.datetime(1970,1,1)).dt.total_seconds()

NameError: name 'dt' is not defined

Any thoughts? Thank you.

Chubaka
  • 2,933
  • 7
  • 43
  • 58

3 Answers3

1

Instead of doing it manually, you can just convert it to datetime and use timestamp()

Something like this.

from datetime import datetime

s = '2017-08-16'
epoch = datetime.strptime(s, "%Y-%m-%d").timestamp()
print(epoch)
# Output -- 1502821800.0
DM_Morpheus
  • 710
  • 2
  • 7
  • 20
0

try with pd.DateTimeIndex and multiply of 1000 is to make it milliseconds ( you can ignore multiplication if you want in seconds)

  df['Date'] = (pd.DatetimeIndex(df['Date']).astype(np.int64) // 10**9) * 1000

print(df)

         Date
1502841600000
1502928000000
1503014400000
user96564
  • 1,578
  • 5
  • 24
  • 42
0

Try this:

from datetime import datetime as dt

# String for the date
s = '2017-08-16'

#Convert string to datetime
s_dt = dt.strptime(s, '%Y-%m-%d')

#Initialize epoch
epoch = dt.utcfromtimestamp(0)

#Get your difference from epoch in ms
linux_time = (s_dt - dt.utcfromtimestamp(0)).total_seconds()*1000

#Your output
linux_time
1502841600000.0

This is a code for a single date object. You could create a function and use lambda to apply it to the pandas column.

Hope this helps.

Sagar Dawda
  • 1,126
  • 9
  • 17