Rounding up to nearest 30 minutes in python

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

    to round forward you can use :

    #!/usr/bin/env python3
    from datetime import datetime, timedelta
    
    def ceil_dt(dt, delta):
        return dt + (datetime.min - dt) % delta
    
    now = datetime.now()
    print(now)    
    print(ceil_dt(now, timedelta(minutes=30)))
    

    To round back to the nearest 30th minute

    def rounded_to_the_last_30th_minute_epoch():
        now = datetime.now()
        rounded = now - (now - datetime.min) % timedelta(minutes=30)
        return rounded
    

提交回复
热议问题