Rounding time in Python

前端 未结 8 2000
清酒与你
清酒与你 2020-12-24 13:34

What would be an elegant, efficient and Pythonic way to perform a h/m/s rounding operation on time related types in Python with control over the rounding resolution?

8条回答
  •  [愿得一人]
    2020-12-24 13:53

    How about use datetime.timedeltas:

    import time
    import datetime as dt
    
    hms=dt.timedelta(hours=20,minutes=11,seconds=13)
    
    resolution=dt.timedelta(seconds=10)
    print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
    # 0:00:03
    
    resolution=dt.timedelta(minutes=10)
    print(dt.timedelta(seconds=hms.seconds%resolution.seconds))
    # 0:01:13
    

提交回复
热议问题