Rounding time in Python

前端 未结 8 2065
清酒与你
清酒与你 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:58

    This will round up time data to a resolution as asked in the question:

    import datetime as dt
    
    current = dt.datetime.now()
    current_td = dt.timedelta(hours=current.hour, minutes=current.minute, seconds=current.second, microseconds=current.microsecond)
    
    # to seconds resolution
    to_sec = dt.timedelta(seconds=round(current_td.total_seconds()))
    print(dt.datetime.combine(current, dt.time(0)) + to_sec)
    
    # to minute resolution
    to_min = dt.timedelta(minutes=round(current_td.total_seconds() / 60))
    print(dt.datetime.combine(current, dt.time(0)) + to_min)
    
    # to hour resolution
    to_hour = dt.timedelta(hours=round(current_td.total_seconds() / 3600))
    print(dt.datetime.combine(current, dt.time(0)) + to_hour)
    

提交回复
热议问题