将值四舍五入到最接近的小时

时间:2021-02-06 19:02:27

标签: python python-3.x pandas datetime

这是我第一次在这里发帖提问,如果我没有把问题解释的很清楚,请给我一个改进提问方式的机会。谢谢!

我有一个包含这样的日期和时间的数据集

TIME                  COL1         COL2         COL3 ...
2018/12/31 23:50:23    34           DC           23
2018/12/31 23:50:23    32           NC           23
2018/12/31 23:50:19    12           AL           33
2018/12/31 23:50:19    56           CA           23
2018/12/31 23:50:19    98           CA           33

我想创建一个新列,格式类似于“2018-12-31 11:00:00 PM”而不是“2018/12/31 23:10:23”,17:40 被四舍五入到 6:00

我尝试使用 .dt.strftime("%Y-%m-%d %H:%M:%S") 更改格式,然后当我尝试将时间从 12 小时转换为 24 小时时,我卡在这里。

Name: TIME, Length: 3195450, dtype: datetime64[ns]

我发现 df['TIME'] 的类型是 pandas.core.series.Series

现在我不知道如何继续。请给我一些想法、提示或任何说明。非常感谢!

1 个答案:

答案 0 :(得分:1)

从您的示例来看,您似乎想按小时计算,而不是圆形?在任何情况下,首先确保您的 TIME 列是 datetime dtype。

df['TIME'] = pd.to_datetime(df['TIME'])

现在使用 dt accessoroffset alias 的地板(或圆形):

df['newTIME'] = df['TIME'].dt.floor('H') # could use round instead of floor here

# df['newTIME'] 
# 0   2018-12-31 23:00:00
# 1   2018-12-31 23:00:00
# 2   2018-12-31 23:00:00
# 3   2018-12-31 23:00:00
# 4   2018-12-31 23:00:00
# Name: newTIME, dtype: datetime64[ns]

之后,您可以格式化为所需格式的字符串,再次使用 dt 访问器访问日期时间系列的属性:

df['timestring'] = df['newTIME'].dt.strftime("%Y-%m-%d %I:%M:%S %p")

# df['timestring']
# 0    2018-12-31 11:00:00 PM
# 1    2018-12-31 11:00:00 PM
# 2    2018-12-31 11:00:00 PM
# 3    2018-12-31 11:00:00 PM
# 4    2018-12-31 11:00:00 PM
# Name: timestring, dtype: object