Sachin Kumar
Sachin Kumar

Reputation: 75

How to convert datetime index into some decimal number?

I have this data frame where data is sorted based on time starting at around 9:15:00. Using df['t_factor'] = df.index.strftime("%H:%M:%S") i converted index into only time values in an extra column. Now in this column, I want to represent this time with some decimal number, like say for 9:15:00 I want this to be converted into 9.25. Any idea how to do it in a single line?

The conversion formula is something like "9+15/60+0/3600", but I don't know how to access H, M, and S separately and write in a single line for the whole column.

Reference image enter image description here

Upvotes: 0

Views: 272

Answers (1)

norie
norie

Reputation: 9857

You could do this using the original index rather than the new column, especially since the new column will be text.

df["time_num"] = (
    df["Time"].dt.hour + df["Time"].dt.minute / 60 + df["Time"].dt.second / 3600
)

P.S. Are you sure you need to include seconds?

Upvotes: 1

Related Questions