Find current time span in python?

How to find the nearest 15 (or 10) minute interval in python? eg.

>>> datetime.datetime.now()
datetime.datetime(2011, 2, 22, 15, 43, 18, 424873)

I need the current 15 minute interval (15: 30-15: 44), so I would like to convert the above time and

datetime.datetime(2011, 2, 22, 15, 30, 00, 00)
+5
source share
4 answers

The easiest way for me:

from datetime import datetime, timedelta
now = datetime.now()
now = now - timedelta(minutes = now.minute % 15, seconds = now.second, microseconds = now.microsecond )

Hope this helps.

+4
source

I think for this case using replace is more straight forward than timedelta :

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.replace(minute=(now.minute - (now.minute % 15)), second=0, microsecond=0)
datetime.datetime(2012, 3, 23, 11, 15)
>>> 
+1
source

min = min - min %  15 

(, ,..) 0

0

All Articles