1

I am first taking an epoch timestamp and converting it to a UTC dt using:

d = datetime.utcfromtimestamp(input_epoch)

Using the following SO post: How can I get hours from a Python datetime?, i am then grabbing the hour:

h = d.hour + d.minute / 60. + d.second / 3600

But this maps an epoch that translates to whatever-10:59:59AM to 10AM. I want a function that will map a given epoch to the closest hour using rounding, e.g., hour:00:00-> hour:00:30:00 -> hour, hour:30:01-> hour:59:59 -> hour+1.

My current best idea is to do:

d = datetime.utcfromtimestamp(input_epoch+3600/2)

But I am not convinced this is correct. Is there another builtin library function that will do this more rigorously?

Community
  • 1
  • 1
Tommy
  • 12,588
  • 14
  • 59
  • 110
  • why not just add 30 minutes? if the minutes are over 30 then adding 30 more will change the time to the next hour. So what you have should work just fine but you could change it to 1800 instead of 3600/2 – SirParselot Oct 07 '15 at 14:15
  • note: there is a large difference between `d.second / 3600` and `d.second / 3600.` in Python 2 (the post that you've linked uses the latter). – jfs Oct 07 '15 at 16:26
  • @J.F.Sebastian: Which gives me an excuse to remind people: Just use Py3 syntax when you can! I start basically every file with `from __future__ import absolute_import, division, print_function`, because I work in both Py2 and Py3, and it's a pain to need to switch thinking all the time. (Yes, I know, not always possible with existing code) – ShadowRanger Oct 07 '15 at 16:49

2 Answers2

1

Adding 30 minutes and truncating the result to an hour is the correct method if you want to use "round half up" tie-breaking rule for positive timestamps (input_epoch > 0):

d = datetime.utcfromtimestamp(3600 * ((input_epoch + 1800) // 3600))
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

I'd go with

h = d.hour + (d.minute + 30 + (d.second + 30) / 60) / 60

if hour:29:30 should also result in hour+1.

causa prima
  • 1,502
  • 1
  • 14
  • 24