While converting a panda
object to a timestamp, I am facing this strange issue.
Train['date'] value is like 01/05/2014
which I am trying to convert into linuxtimestamp.
My code:
Train = pd.read_csv("data.tsv", sep='\t') # use TAB as column separator
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
And I get this error:
Traceback (most recent call last):
File "socratis.py", line 11, in <module>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
File "/home/ubuntu/.local/lib/python2.7/site-packages/pandas/core/series.py", line 2220, in apply
mapped = lib.map_infer(values, f, convert=convert_dtype)
File "pandas/src/inference.pyx", line 1088, in pandas.lib.map_infer (pandas/lib.c:62658)
File "socratis.py", line 11, in <lambda>
Train['timestamp'] = pd.to_datetime(Train['date']).apply(lambda a: a.timestamp())
AttributeError: 'Timestamp' object has no attribute 'timestamp'
to_datetime seems to be deprecated. Use to_pydatetime()
instead...
You're looking for datetime.timestamp()
, which was added in Python 3.3. Pandas itself isn't involved.
N.B.
.timestamp()
will localize naive timestamps to the computer's UTC offset. To the contrary, suggestions in this answer are timezone-agnostic.
Since pandas uses nanoseconds internally (numpy datetime64[ns]), you should be able to do this even with Python 2:
Train['timestamp'] = pd.to_datetime(Train['date']).value / 1e9
Or be more explicit wtih something like this (from the datetime docs):
import pandas as pd
from datetime import datetime, timedelta
def posix_time(dt):
return (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)
Train['timestamp'] = pd.to_datetime(Train['date']).apply(posix_time)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With