2

I'm following a course where I have to convert a date to a unix timestamp.

import pandas as pd

df = pd.read_csv('file.csv')
print type(df.iloc[-1].name)

class 'pandas.tslib.Timestamp'

ts = df.iloc[-1].name.timestamp()

AttributeError: 'Timestamp' object has no attribute 'timestamp'

3
  • 3
    Seems like the Timestamp class doesn't provide a timestamp() method. Is it supposed to? Commented Jun 21, 2016 at 13:13
  • 2
    What are you trying to do ? Commented Jun 21, 2016 at 13:16
  • Hi - did either my response or @MaxU's response help so solve your problem? If so, it would be great if you could mark the question as answered. Commented Jun 23, 2016 at 8:51

2 Answers 2

1

You don't actually ask a question (tip for next time: be more explicit), but I assume you want an epoch / Unix timestamp from a Pandas Timestamp object.

If you use the pandas.tslib.Timestamp.value method, you'll return the timestamp in microseconds (1/1,000,000 second):

In [1]: import pandas as pd

In [2]: date_example = pd.to_datetime("2016-06-21")

In [3]: type(date_example)
Out[3]: pandas.tslib.Timestamp

In [4]: date_example.value
Out[4]: 1466467200000000000

If you prefer you can simply divide by 1000 to get milliseconds or 1000000 to get whole seconds, eg:

In [5]: date_example.value / 1000000
Out[5]: 1466467200000
Sign up to request clarification or add additional context in comments.

Comments

0

IIUC, you can do it this way:

generate sample DF with datetime dtype

In [65]: x = pd.DataFrame({'Date': pd.date_range('2016-01-01', freq='5D', periods=5)})

In [66]: x
Out[66]:
        Date
0 2016-01-01
1 2016-01-06
2 2016-01-11
3 2016-01-16
4 2016-01-21

convert datetime to UNIX timestamp

In [67]: x.Date.astype(np.int64) // 10**9
Out[67]:
0    1451606400
1    1452038400
2    1452470400
3    1452902400
4    1453334400
Name: Date, dtype: int64

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.