Search code examples
pandasdataframedatetimetimestampdatetimeindex

Whats is the most common way to convert a Timestamp to an int


I tried multiple ways but they always give me an error. The most common error I get is :

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

Here is the line where I try to convert my element :

df.index.map(lambda x: x - oneSec if (pandas.to_datetime(x).astype(int) / 10**9) % 1 else x)

I tried x.astype(int) or x.to_datetime().astype(int)


Solution

  • I think here is necessary use Index.where:

    df = pd.DataFrame(index=(['2019-01-10 15:00:00','2019-01-10 15:00:01']))
    
    df.index = pd.to_datetime(df.index)
    
    mask = df.index.second == 1
    print (mask)
    [False  True]
    
    df.index = df.index.where(~mask, df.index - pd.Timedelta(1, unit='s'))
        
    print (df)
    Empty DataFrame
    Columns: []
    Index: [2019-01-10 15:00:00, 2019-01-10 15:00:00]