A.Boss
A.Boss

Reputation: 217

pandas datetime to unixtime

I want to change Datetime (2014-12-23 00:00:00) into unixtime. I tried it with the Datetime function but it didn´t work. I got the Datetime stamps in an array.

Zeit =np.array(Jahresgang1.ix[ :,'Zeitstempel'])
t = pd.to_datetime(Zeit, unit='s')
unixtime = pd.DataFrame(t)
print unixtime

Thanks a lot

Upvotes: 7

Views: 6320

Answers (2)

FObersteiner
FObersteiner

Reputation: 25654

to emphasize EdChum's first comment, you can directly get Unix time like

import pandas as pd

s = pd.to_datetime(["2014-12-23 00:00:00"])
unix = s.astype("int64")

print(unix)
# Int64Index([1419292800000000000], dtype='int64')

or for a pd.Timestamp:

print(pd.to_datetime("2014-12-23 00:00:00").value)
# 1419292800000000000

Notes

  • the output precision is nanoseconds - if you want another, divide appropriately, e.g. by 10⁹ to get seconds, 10⁶ to get milliseconds etc.
  • this assumes the input date/time to be UTC, unless a time zone / UTC offset is specified

Upvotes: 0

EdChum
EdChum

Reputation: 394409

I think you can subtract the date 1970-1-1 to create a timedelta and then access the attribute total_seconds:

In [130]:    
s = pd.Series(pd.datetime(2012,1,1))
s

Out[130]:
0   2012-01-01
dtype: datetime64[ns]

In [158]:
(s - dt.datetime(1970,1,1)).dt.total_seconds()

Out[158]:
0    1325376000
dtype: float64

Upvotes: 8

Related Questions