Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round timestamp to nearest day in Python

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 to round these seconds to the nearest day e.g. if:

datetime.fromtimestamp(sec_since_epoch)

corresponds to datetime(2013, 12, 14, 5, 0, 0)

I want the new timestamp to correspond to datetime(2013, 12, 14, 0, 0, 0)

I know the ugly way of doing it, but is there an elegant way ?

like image 760
Lyman Zerga Avatar asked Oct 31 '13 23:10

Lyman Zerga


People also ask

How do I convert a timestamp to a date in python?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

How do you round Timedelta in Python?

To round the Timedelta with specified resolution, use the timestamp. round() method. Set the hourly frequency resolution using the freq parameter with value H.


1 Answers

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

like image 134
Eugene Naydenov Avatar answered Sep 17 '22 12:09

Eugene Naydenov