关于python:将pandas的日期时间转换为小时:分钟四舍五入到15分钟

Turn pandas datetime to hour:min rounded to 15 min

我使用以下命令使用pandas阅读此excell工作表(仅\\'DATEHEUREMAX \\'列):

1
xdata = read_excel('Data.xlsx', 'Data', usecols=['DATEHEUREMAX'])

exemple of my excel sheet

现在我想将此df转换为简化的df,仅将hour:min向上舍入为15min。主要思想是根据小时:分钟

绘制直方图


无需四舍五入即可获得DATEHEUREMAX列的日期直方图。为此,您可以仅使用pd.Grouper,如下所述。

玩具样本代码

您可以算出以下示例来获取日期列的解决方案:

1
2
3
4
5
6
7
8
9
10
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Generating a sample of 10000 timestamps and selecting 500 to randomize them
df = pd.DataFrame(np.random.choice(pd.date_range(start=pd.to_datetime('2015-01-14'),periods = 10000, freq='S'), 500),  columns=['date'])
# Setting the date as the index since the TimeGrouper works on Index, the date column is not dropped to be able to count
df.set_index('date', drop=False, inplace=True)
# Getting the histogram
df.groupby(pd.Grouper(freq='15Min')).count().plot(kind='bar')
plt.show()

此代码解析为如下图所示的图形:
enter image description here

数据解决方案

对于您的数据,您应该可以执行以下操作:

1
2
3
4
5
6
import pandas as pd
import matplotlib.pyplot as plt
xdata = read_excel('Data.xlsx', 'Data', usecols=['DATEHEUREMAX'])
xdata.set_index('DATEHEUREMAX', drop=False, inplace=True)
xdata.groupby(pd.Grouper(freq='15Min')).count().plot(kind='bar')
plt.show()


请考虑以下具有单个列的DataFrame,将其读取为日期时间(不是字符串):

1
2
3
4
5
                  Dat
0 2019-06-03 12:07:00
1 2019-06-04 10:04:00
2 2019-06-05 11:42:00
3 2019-06-06 10:17:00

将这些日期四舍五入到15分钟:

1
df['Dat2'] = df.Dat.dt.round('15T').dt.time.map(lambda s: str(s)[:-3])

结果是:

1
2
3
4
5
                  Dat  Dat2
0 2019-06-03 12:07:00 12:00
1 2019-06-04 10:04:00 10:00
2 2019-06-05 11:42:00 11:45
3 2019-06-06 10:17:00 10:15

出于演示目的,我将结果保存在一个新列中,但是您可以
将其保存在原始列中。


我想这就是你要的

1
rounded_column = df['time_column'].dt.round('15min').strftime("%H:%M")

尽管我同意评论者的意见,但您可能并不需要这样做,而只是使用时间分组器