0

I have timestamps that are calculated by a given interval. Ex: timestamp being 193894 and interval being 20000. The time is calculated by doing 193894/20000 = 9.6947. 9.6947 being 9 minutes and 0.6947 of a minute in seconds (0.6947 * 60) = 42 s (rounded up) thus the human readable timestamp being 9 min 42 sec.

Is there a Pythonic (assuming there is some library) way of doing this rather than doing a silly math calculation like this for every timestamp?

The reason being is because if timestamp is 1392338 (1 hour 9 min 37 sec) something that yields in the hours range, I want to be able to keep it dynamic.

I am just wondering if there was a better way to do this than the mathematical calculation way.

user1757703
  • 2,925
  • 6
  • 41
  • 62
  • http://stackoverflow.com/a/539360/4323 – John Zwinck Jul 03 '14 at 02:25
  • possible duplicate of [Python format timedelta to string](http://stackoverflow.com/questions/538666/python-format-timedelta-to-string) – Brandon Taylor Jul 03 '14 at 02:37
  • I don't think this is quite a dupe of that question. The OP doesn't have a `timedelta` object to start with, or even an absolute number of seconds. The OP also wants seconds to be rounded up, not down. – dano Jul 03 '14 at 03:49

1 Answers1

2

The linked question can help you actually format timedelta object once you have it, but there are a few tweaks you need to make to get the exact behavior you want

from __future__ import division

from datetime import timedelta
from math import ceil

def get_interval(timestamp, interval):
    # Create our timedelta object
    td = timedelta(minutes=timestamp/interval)
    s = td.total_seconds()
    # This point forward is based on http://stackoverflow.com/a/539360/2073595
    hours, remainder = divmod(s, 3600)
    minutes = remainder // 60
    # Use round instead of divmod so that we'll round up when appropriate.
    # To always round up, use math.ceil instead of round.
    seconds = round(remainder - (minutes * 60))
    return "%d hours %d min %d sec" % (hours, minutes, seconds)

if __name__ == "__main__:
    print print_interval(1392338, 20000)
    print get_interval(193894, 20000)

Output:

1 hours 9 min 37 sec
0 hours 9 min 42 sec
dano
  • 91,354
  • 19
  • 222
  • 219