2

Using timestamps, datetimes is not always convenient. Some programs expect simple numeric input. When pandas Timestamps are collected in a pandas.Series it is easy to convert them to numeric values and back.

import pandas as pd
from pandas import Timestamp

age = [30, 31, 31]
date = [Timestamp('2001-02-10 00:01:00'),
 Timestamp('2001-11-12 00:01:00'),
 Timestamp('2002-02-27 00:01:00')]

df = pd.DataFrame({'age': age, 'date': date})

pd.to_numeric(df.date)
0     981763260000000000
1    1005523260000000000
2    1014768060000000000

Though converting a single pandas or numpy datetime object or a timedelta to numeric does not work like that.

pd.to_numeric(Timestamp('2001-02-10 00:01:00'))
pd.to_numeric([Timestamp('2001-02-10 00:01:00')])
pd.to_numeric([numpy.datetime64('2001-02-10T00:01:00.000000000')])
pd.to_numeric([pd.Timedelta('365 days')])
# all give:
#> TypeError: Invalid object type at position 0

What are proper ways to convert these types to numeric types?

2
  • @jpp: I don't want the generate a Series or DataFrame just to convert a Datetime to a numeric value. The first two questions address Series and DataFrames. The third question is about conversion between datetime, Timestamp and datetime64. It is actually not about numeric values at all. The last question is somewhat what I am looking for, but also very specific. So, I don't think this is a duplicate question. Commented Jun 22, 2018 at 21:00
  • Possible duplicate: Converting between datetime, Timestamp and datetime64. In particular, this answer. Commented Jun 22, 2018 at 22:05

3 Answers 3

1

Just use the ts.value attribute of the timestamp ts:

ts = Timestamp('2001-02-10 00:01:00')
print(ts.value)
#981763260000000000
Sign up to request clarification or add additional context in comments.

Comments

0

Try the methods of the pandas.Timestamp class:

>>> Timestamp('2001-02-10 00:01:00').timestamp()
981763260.0

1 Comment

The return value of .timestamp() is inconsistent with pd.to_numeric().
0

Converting timedelta to numeric:

x = pd.Timedelta('365 days')
x
#Timedelta('365 days 00:00:00')

type(x)
#pandas._libs.tslibs.timedeltas.Timedelta

y = x / np.timedelta64(1, 'D')
y
#365.0

type(y)
#float

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.