Round timestamp to nearest day in Python

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.


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)

You can use datetime.timetuple() to manipulate with the date. E.g. in this way:

from datetime import datetime


dt = datetime(2013, 12, 14, 5, 0, 0)
dt = datetime(*dt.timetuple()[:3]) # 2013-12-14 00:00:00
print dt.strftime('%s') # 1386997200

DEMO