Rounding up to nearest 30 minutes in python

后端 未结 9 618
名媛妹妹
名媛妹妹 2020-11-30 08:07

I have the following code below.

I would like to roundup TIME to the nearest 30 minutes in the hour. For example: 12:00PM or 12:30PM and so on.

EASTE         


        
9条回答
  •  天命终不由人
    2020-11-30 08:15

    >>> from dateutil.rrule import rrule, MINUTELY
    >>> import datetime
    >>> import bisect
    >>> times = list(rrule(MINUTELY,interval=30,dtstart=datetime.date.today(),count=
    48))
    >>> print times[bisect.bisect(times,datetime.datetime.now())]
    2015-09-22 11:00:00
    >>>
    

    Note that this solution uses the 3rd party dateutil library that can be installed with pip install dateutil... Of course, you could solve it without it... but it's easier with it.

提交回复
热议问题