2

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, I want to know if there are different hours in my index. For example, if I have two dates d1 = 2020-01-01 00:00:00 and d2 = 2020-01-02 00:00:00 I can't assume I should apply a smooth operator by hour because makes no sense.

So what I want to know is: how do I know if a day has different hours/minutes or seconds?

Thank you in advance

Hélio Domingos
  • 31
  • 1
  • 1
  • 3
  • Have you checked the [dt accessor](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.html)? – Mephy Apr 18 '20 at 00:33
  • Does this answer your question? [Pandas: Return Hour from Datetime Column Directly](https://stackoverflow.com/questions/25129144/pandas-return-hour-from-datetime-column-directly) – AMC Apr 18 '20 at 02:54

2 Answers2

8

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.

                     0                time       dates  hour  minute  second
0  2020-01-01 06:31:00 2020-01-01 06:31:00  2020-01-01     6      31       0
1  2020-03-12 10:21:09 2020-03-12 10:21:09  2020-03-12    10      21       9
hanchau
  • 89
  • 2
  • https://stackoverflow.com/questions/25129144/pandas-return-hour-from-datetime-column-directly – AMC Apr 18 '20 at 02:54
1

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.

Saurabh P Bhandari
  • 6,014
  • 1
  • 19
  • 50
  • https://stackoverflow.com/questions/25129144/pandas-return-hour-from-datetime-column-directly – AMC Apr 18 '20 at 02:54