我如何将日期时间对象四舍五入到最近的前一个四分之一小时?

问题描述:

假设我有日期时间对象。我希望将它们四舍五入到最近的前一个季度小时:

Let say I have datetime objects. I would like them rounded to the nearest preceding quarter hour:

2014-07-18T14:23:12 --> 2014-07-18T14:15:00
2014-07-18T14:14:59 --> 2014-07-18T14:00:00
2014-07-18T00:00:00 --> 2014-07-18T00:00:00

等。

rounded_qtr_hour = lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,
                                                15*(dt.minute // 15))

基本上,您创建了一个新对象(修改旧的方法是一种功能较弱的方法),将等价的年,月,日,小时,并将分钟四舍五入到最后15分钟间隔(//是楼层划分)。

Basically, you make a new object (modifying the old one is a less functional approach), with equivalent year, month, day, hour, and round the minute down to the last 15 minute interval (// is floor division).