Reputation: 9165
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?
Upvotes: 2
Views: 2349
Reputation: 96
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
Upvotes: 0
Reputation: 57085
Just use the ts.value
attribute of the timestamp ts
:
ts = Timestamp('2001-02-10 00:01:00')
print(ts.value)
#981763260000000000
Upvotes: 1
Reputation: 352
Try the methods of the pandas.Timestamp class:
>>> Timestamp('2001-02-10 00:01:00').timestamp()
981763260.0
Upvotes: 0