Home > front end >  Converting pandas._libs.tslibs.timestamps.Timestamp to seconds since midnight?
Converting pandas._libs.tslibs.timestamps.Timestamp to seconds since midnight?

Time:01-13

I have a pandas._libs.tslibs.timestamps.Timestamp object, e.g., 2016-01-01 07:00:04.85 00:00 and I want to create an int object that stores the number of seconds since the previous midnight.

In the above example, it would return 7 * 3600 0 * 60 4.85 = 25204.85 Is there a quick way to do this in pandas?

CodePudding user response:

You can use normalize() to subtract the date part:

# ts = pd.to_datetime('2016-01-01 07:00:04.85 00:00')
>>> (ts - ts.normalize()).total_seconds()
25204.85

It also works with DataFrame through dt accessor:

# df = pd.DataFrame({'date': [ts]})
>>> (df['date'] - df['date'].dt.normalize()).dt.total_seconds()
0    25204.85
Name: date, dtype: float64

CodePudding user response:

Not sure if this is what you are looking for but here is an implementation:

import pandas as pd

def seconds_from_midnight(date):
    return date.hour * 3600   date.minute * 60   date.second   date.microsecond / 1000000

date = pd.Timestamp.now()
print(date)
print(seconds_from_midnight(date))
  • Related