Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError: 'Timestamp' object has no attribute 'timestamp

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'
like image 771
user3449212 Avatar asked Sep 11 '16 10:09

user3449212


2 Answers

to_datetime seems to be deprecated. Use to_pydatetime() instead...

like image 150
ntg Avatar answered Sep 21 '22 09:09

ntg


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)
like image 38
patricktokeeffe Avatar answered Sep 18 '22 09:09

patricktokeeffe