5

How can I find the nearest 15 (or 10) minute interval in python ? e.g.

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

I'd like the current 15 minute interval (15:30-15:44) so I'd like to transform the above datetime to a

datetime.datetime(2011, 2, 22, 15, 30, 00, 00) 

4 Answers 4

5

Quite the easiest way to me:

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

Hope that'll help.

Sign up to request clarification or add additional context in comments.

Comments

2

I think for this case using replace is more straightforward 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) >>> 

2 Comments

also need to replace minutes & seconds to zero
@cfl: You meant seconds & microseconds. Thanks, I've edited the example.
0

Look at timedelta()

http://docs.python.org/release/2.5.2/lib/datetime-timedelta.html

Comments

0

Just set minutes on

min = min - min % 15 

and set shorter time units (seconds, msec, ..) on 0

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.