Round timestamp to nearest day in Python

前端 未结 3 865
天命终不由人
天命终不由人 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:20

    Sure, just convert the datetime to a date first:

    sec_since_epoch = (date_obj.date() - date(1970, 1, 1)).total_seconds()
    

    Of course date() truncates. If you want to round up if on or after noon, etc., just add 12 hours before truncating, or check whether the date is >= noon on the same day and if so add a day (note that these can do different things on DST boundary days), or whatever rule you want to round by.

提交回复
热议问题