4

I'd like to round down/floor an epoch/Unix timestamp so as to remove the seconds.

I'm using Python 2.x and Python 3.x

E.g.

1488728901 = Sun, 05 Mar 2017 15:48:21 GMT

to:

1488728880 = Sun, 05 Mar 2017 15:48:00 GMT

There's some great answers by using datetime to manipulate the time but it seems OTT if my input and output are integers.

Alastair McCormack
  • 25,004
  • 7
  • 71
  • 96

2 Answers2

11

A simple bit of maths:

int(timestamp//60 * 60)

(// replicates Python 2.x division (/) where the result is a whole number)

Alastair McCormack
  • 25,004
  • 7
  • 71
  • 96
  • 3
    In case this seems too simplistic: this works because Unix timestamps increase with 86400 every day. This is true for days including [leap seconds](https://stackoverflow.com/questions/16539436/unix-time-and-leap-seconds) as well. @alastair I am sure that you already knew this - just added this for the benefit of other skeptics finding this answer. – bohrax Sep 13 '18 at 06:43
  • Love it! Super simple! – kakhkAtion Oct 03 '19 at 23:28
  • As @bohrax alluded to, you can do the same thing with hours, days, etc. e.g. `(int(time.time()) // 86400) * 86400` – Cfomodz May 27 '22 at 17:20
3

Or if you're not clever you could use arrow:

>>> import arrow
>>> timestamp = arrow.get(1488728901)
>>> timestamp
<Arrow [2017-03-05T15:48:21+00:00]>
>>> timestamp = timestamp.floor('minute')
>>> timestamp.format('YYYY-MMM-DD HH:mm:ss')
'2017-Mar-05 15:48:00'
Bill Bell
  • 20,186
  • 5
  • 41
  • 55