2

I have the variable time:

>>> time = pd.to_datetime(1613260800000000000)
>>> time
Timestamp('2021-02-14 00:00:00')

time is a timestamp. Now I want to convert time back to an int value. But Timestamp object has no attribute astype. Running the following code:

>>>time.astype(int)

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

I know that for a column of a dataframe I can do:

>>> df['start_time'] = df['start_time'].to_timedate()
>>> df['start_time'] = df['start_time'].astype(int)

The second command assigns the type of the column to int.

But I did not find a comprehensive source explaining what to do with individual Timestamp argument.

How can I solve this issue?

Hadi Rohani
  • 215
  • 4
  • 14

2 Answers2

4

just use time_variable.timestamp()

but that will be in seconds ... instead of ms or whatever (us?)

you will need to multiply the result by 1e9 to get back the same value as you put in

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
2

For ns like native format for numpy/pandas use:

d = pd.to_datetime(1613260800000000000)

native = int(d.timestamp() * 10**9)
print (native)
1613260800000000000

print (pd.to_datetime(native))
2021-02-14 00:00:00

If need convert column:

time = pd.to_datetime(1613260800000000000)

df = pd.DataFrame({'start_time':[time, time]})

print (df['start_time'].astype(np.int64))
0    1613260800000000000
1    1613260800000000000
Name: start_time, dtype: int64
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252