Habalusa
Habalusa

Reputation: 1800

Find current time interval in python?

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)

Upvotes: 5

Views: 3128

Answers (4)

Jeffrey Bauer
Jeffrey Bauer

Reputation: 14090

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)
>>> 

Upvotes: 2

Luka Rahne
Luka Rahne

Reputation: 10517

Just set minutes on

min = min - min %  15 

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

Upvotes: 0

Gandi
Gandi

Reputation: 3652

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.

Upvotes: 5

Related Questions