1

I have a column of time in my pandas DataFrame containing more than 800,000 rows. The time format is something like this:

08:28:31
08:28:35
08:28:44
08:28:44

I want to convert this format into hourly, which means if the first time comes 08:28:31 then the second-time time should come in hour by hour 09:28:31 etc. How do we achieve this in python using the DateTime library

output data:

08:28:31
09:28:31
...
23:28:31

08:28:35
09:28:35
...
23:28:35

08:28:44
...
08:28:44
...
6
  • Please Rephrase , that what you are asking . I cant understand Commented Mar 8, 2021 at 9:57
  • Does this answer your question? How to change the datetime format in pandas Commented Mar 8, 2021 at 9:58
  • @jezrael yes exactly! Commented Mar 8, 2021 at 10:01
  • 3rd ->10:28:31 , 4th-> 11:28:31, 5th->12:28:31 and so on ! Commented Mar 8, 2021 at 10:03
  • 1
    yes ! exactly . Commented Mar 8, 2021 at 10:04

1 Answer 1

1

Use:

#convert values to datetimes
df['date'] = pd.to_datetime(df['date'])

#count number of repeated values
df = df.loc[df.index.repeat(24 - df['date'].dt.hour)]
#generate hour timedeltas
hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H')

#add to dates and generate times with convert index to default values
s = df['date'].add(hours).dt.time.reset_index(drop=True)
print (s)
0     08:28:31
1     09:28:31
2     10:28:31
3     11:28:31
4     12:28:31
  
59    19:28:44
60    20:28:44
61    21:28:44
62    22:28:44
63    23:28:44
Length: 64, dtype: object
Sign up to request clarification or add additional context in comments.

4 Comments

What if we want to take the time after every 15 minutes . Is it possible ?
@OfficialDeveloper - Can you try change hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='H') to hours = pd.to_timedelta(df.groupby(level=0).cumcount(), unit='Min') * 15 ?
As you told me that Use df.groupby('Time', as_index=False)['Price'].mean() , if duplicates occurs , I have to take the mean of only duplicated rows not entire column
@OfficialDeveloper - yop, but if use mean of not duplicates get same values, so solution working well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.