Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
996 views
in Technique[技术] by (71.8m points)

python - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...