Round timestamp to nearest day in Python

前端 未结 3 867
天命终不由人
天命终不由人 2021-01-18 03:14

In Python 2.7.2 I am getting the seconds since epoch using:

sec_since_epoch = (date_obj - datetime(1970, 1, 1, 0, 0)).total_seconds()

Now I want

3条回答
  •  一整个雨季
    2021-01-18 03:22

    Here's a pretty intuitive way, it may be a little barbaric looking but it works in one line.

    Basically, the logic is get your current date, then subtract all the hours minutes, second and microseconds you have, and then add one day ( that's if you want to round up, otherwise just leave it if you're rounding down.)

       from datetime import date,timedelta
    
        Rounded_date =  ( the_date - timedelta(hours=date.hour, minutes=date.minute,
        seconds=date.second, microseconds=date.microsecond) ) + timedelta(days=1)
    

提交回复
热议问题