Rounding up to nearest 30 minutes in python

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

    Round up to nearest amount specified in minutes via round_mins without using third-party libraries and just a few lines of code.

    import datetime
    round_mins = 30
    now = datetime.datetime.now()
    mins = now.minute - (now.minute % round_mins)
    print datetime.datetime(now.year, now.month, now.day, now.hour, mins) + datetime.timedelta(minutes=round_mins)
    
    0 讨论(0)
  • 2020-11-30 08:38

    this should work too, not sure about time zones though

    rounded=time.gmtime(30*60*(round(time.time()/(30*60))))
    
    0 讨论(0)
  • 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'.

    0 讨论(0)
提交回复
热议问题