Rounding up to nearest 30 minutes in python

后端 未结 9 617
名媛妹妹
名媛妹妹 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:24

    You can divide your minutes by 30, round that and multiply by 30 again to get either 0, 30 or 60 minutes:

    date = datetime.datetime(2015, 9, 22, 12, 35)
    approx = round(date.minute/30.0) * 30
    
    date = date.replace(minute=0)
    date += datetime.timedelta(seconds=approx * 60)
    time = date.time()
    print(time.strftime('%H:%M'))
    # prints '13:30'
    

    I'm using a datetime object because timedelta doesn't work with time objects. In the end you can obtain the time using date.time().

提交回复
热议问题