Lyman Zerga
Lyman Zerga

Reputation: 1515

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 ?

Upvotes: 14

Views: 36781

Answers (4)

ntg
ntg

Reputation: 14075

For modern Pandas versions ;), I would consider using the appropriate rounding functions. You have the selection of floor, round and ceil... e.g. for:

t_max_overall=pd.Timestamp('2022-05-05 10:03:33.086966+0000', tz='UTC')

then:

t_max_overall.floor('1d')

Returns:Timestamp('2022-05-05 00:00:00+0000', tz='UTC')

While:

t_max_overall.round('1d')

Returns Timestamp('2022-05-05 00:00:00+0000', tz='UTC'),

And:

t_max_overall.ceil('1d'))

Returns: Timestamp('2022-05-06 00:00:00+0000', tz='UTC')

Upvotes: 3

puistori
puistori

Reputation: 76

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)

Upvotes: 1

Eugene Naydenov
Eugene Naydenov

Reputation: 7295

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

Upvotes: 32

abarnert
abarnert

Reputation: 365607

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.

Upvotes: 11

Related Questions