Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round datetime column to nearest quarter hour

I have loaded a data file into a Python pandas dataframe. I has a datetime column of the format 2015-07-18 13:53:33.280.

What I need to do is create a new column that rounds this out to its nearest quarter hour. So, the date above will be rounded to 2015-07-18 13:45:00.000.

How do I do this in pandas? I tried using the solution from here, but get an 'Series' object has no attribute 'year' error.

like image 600
sfactor Avatar asked Sep 02 '15 04:09

sfactor


People also ask

How do you round datetime to hours?

Round time to nearest hour ( TIME(1,0,0) = 1/24 representing an hour) and add a zero time value to ensure the expression is cast as a Time. M: There isn't an equivalent of MROUND in M, so instead multiply the time by 24 to express it as a number of hours, then round, then divide by 24 and convert to a Time type.


1 Answers

You can use round(freq). There is also a shortcut column.dt for datetime functions access (as @laurens-koppenol suggests).

Here's one-liner:

df['old column'].dt.round('15min')   

String aliases for valid frequencies can be found here. Full working example:

In [1]: import pandas as pd     In [2]: df = pd.DataFrame([pd.Timestamp('2015-07-18 13:53:33.280'),                            pd.Timestamp('2015-07-18 13:33:33.330')],                          columns=['old column'])  In [3]: df['new column']=df['old column'].dt.round('15min')   In [4]: df Out[4]:                 old column          new column 0 2015-07-18 13:53:33.280 2015-07-18 14:00:00 1 2015-07-18 13:33:33.330 2015-07-18 13:30:00 
like image 123
tworec Avatar answered Sep 22 '22 21:09

tworec