Rounding up to nearest 30 minutes in python

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

    Thanks for all the input guys. I solved this with my own approach.

    min_time = timezone.localtime(timezone.now())
    min_time_est = min_time.minute 
    if min_time_est > 30:
        add_mins = 60 - min_time_est
    else:
        add_mins = 30 - min_time_est
    
    EASTERN_NOW = timezone.localtime(timezone.now() + timedelta(minutes=add_mins))
    TIME = datetime.time(EASTERN_NOW.time().hour, EASTERN_NOW.time().minute).strftime(
        VALID_TIME_FORMATS[2])
    

    In case anyone else has a similar problem. The about 'TIME' outputs every 30 mins e.g '1:00PM' or '1:30PM'.

提交回复
热议问题