1

How do I extract just the time portion of datetime64[ns] column formatted 1900-01-01 00:32:59 and convert it into total seconds?

I want the end result to be 1979 in seconds in this example, where we are exactly (32*60 + 59) seconds from 1900-01-01 00:00:00.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
Rafel Taye
  • 11
  • 2
  • Possible duplicate of [Pandas; transform column with MM:SS,decimals into number of seconds](http://stackoverflow.com/questions/20472413/pandas-transform-column-with-mmss-decimals-into-number-of-seconds) – spies006 May 22 '17 at 04:43

1 Answers1

0

You can use to_timedelta + strftime + total_seconds + astype:

df = pd.DataFrame({"date": ["1900-01-01 00:32:59"]})
df['date'] = pd.to_datetime(df['date'])
print (df)
                 date
0 1900-01-01 00:32:59

df['total'] = pd.to_timedelta(df['date'].dt.strftime("%H:%M:%S"))
                .dt.total_seconds().astype(int)
print (df)
                 date  total
0 1900-01-01 00:32:59   1979

Or floor + total_seconds + astype:

df['total'] = (df['date'] - df['date'].dt.floor('D')).dt.total_seconds().astype(int)
print (df)
                 date  total
0 1900-01-01 00:32:59   1979

Or normalize + total_seconds + astype

df['total'] = (df['date'] - df['date'].dt.normalize()).dt.total_seconds().astype(int)
print (df)
                 date  total
0 1900-01-01 00:32:59   1979
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252