Skip to content Skip to sidebar Skip to footer

How To Extract Hours From A Pandas.datetime?

I´ve a pandas dataframe which I applied the pandas.to_datetime. Now I want to extract the hours/minutes/seconds from each timestamp. I used df.index.day to get the days, and now,

Solution 1:

I think you should use df[index].dt provided by pandas. You can extract day, week, hour, minute, second by using it.

Please see this.

dir(df[index].dt)

Here is an example.

import pandas as pd
df = pd.DataFrame([["2020-01-01 06:31:00"], ["2020-03-12 10:21:09"]])
print(df)
df['time'] = pd.to_datetime(df["timestamp"])
df['dates'] = df['time'].dt.date
df['hour'] = df['time'].dt.hour
df['minute'] = df['time'].dt.minute
df['second'] = df['time'].dt.second

Now your df should look like this.

0timedateshourminutesecond02020-01-01 06:31:00 2020-01-01 06:31:00  2020-01-01     631012020-03-12 10:21:09 2020-03-12 10:21:09  2020-03-12    10219

Solution 2:

If d1 and d2 are datetime or Timestamp objects, you can get the hour, minute and second using attributes hour , minute and second

print(d1.hour,d1.minute,d1.second)
print(d2.hour,d2.minute,d2.second)

Similarly, year, month and day can also be extracted.

Post a Comment for "How To Extract Hours From A Pandas.datetime?"