Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - how can I round a datetime object to the most recent previous quarter hour?

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

Etc.

like image 886
tadasajon Avatar asked Jul 18 '14 17:07

tadasajon


People also ask

How do I round datetime column to nearest quarter hour?

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

How do I round up datetime in Python?

In order to round to the nearest 15 minutes we need to use a combination of round and timedelta . In this code example we combine these operations into a simple function whose inputs are the DateTime that will be rounded, and the time window to round towards, which in our case will be 15 minutes.

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

rounded_qtr_hour = lambda dt: datetime.datetime(dt.year, dt.month, dt.day, dt.hour,
                                                15*(dt.minute // 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).

like image 97
metaperture Avatar answered Oct 22 '22 10:10

metaperture