3

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
Soerendip
  • 7,684
  • 15
  • 61
  • 128
  • @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. – Soerendip Jun 22 '18 at 21:00
  • Possible duplicate: [Converting between datetime, Timestamp and datetime64](https://stackoverflow.com/questions/13703720/converting-between-datetime-timestamp-and-datetime64). In particular, [this answer](https://stackoverflow.com/a/21916253/9209546). – jpp Jun 22 '18 at 22:05

3 Answers3

1

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

ts = Timestamp('2001-02-10 00:01:00')
print(ts.value)
#981763260000000000
DYZ
  • 55,249
  • 10
  • 64
  • 93
0

Try the methods of the pandas.Timestamp class:

>>> Timestamp('2001-02-10 00:01:00').timestamp()
981763260.0
Max Feng
  • 352
  • 3
  • 10
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
gcollar
  • 86
  • 1
  • 9