Rounding up to nearest 30 minutes in python

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

    you can just take datetime input apart and ajust time

     def ajustTime():
    
    from datetime import datetime
    
    mytime= datetime.now().strftime("%Y-%m-%d %H-%M")
    
    m = mytime.split()
    
    hours, mints = m[1].split('-')
    
    if 15 <= int(mints) <= 45:
        mints = ':30'
    elif int(mints) < 15:
        mints = ':00'
    elif int(mints) > 45:
        mints = ':00'
        h = int(hours) + 1
        hours = str(h)
    
    print(m[0] + " " + hours + mints)
    

    ajustTime()

    output

    2015-09-22 15:42:03.587633

    2015-09-22 15:30

    2015-09-22 15:46:01.956860

    2015-09-22 16:00

提交回复
热议问题