Issue
I have dataframe with timestamp values and i want to round off the timestamp to upper minute.
But i am not getting the desired output. I have used the following link to do the same:
[1]: http://stackoverflow.com/questions/32344533/how-do-i-round-datetime-column-to-nearest-quarter-hour/32344636
how can i do that using pandas?
example: output:
05:06:34 05:07
05:09:43 05:10
Solution
You can write a function that will round up to the nearest minute:
Code:
import datetime as dt
def round_up_to_minute(timestamp):
return timestamp + dt.timedelta(
seconds=60-timestamp.second,
microseconds=-timestamp.microsecond)
Test Code:
To apply it to a dataframe, you can do something like:
now = dt.datetime.now()
now_plus = now + dt.timedelta(minutes=1)
df = pd.DataFrame(data=[[now, now], [now_plus, now_plus]],
columns=['datetime', 'datetime_rounded'])
df['datetime_rounded'] = df['datetime_rounded'].apply(round_up_to_minute)
print(df)
Results:
datetime datetime_rounded
0 2017-03-06 07:36:54.794 2017-03-06 07:37:00
1 2017-03-06 07:37:54.794 2017-03-06 07:38:00
Answered By - Stephen Rauch
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.