0

I'm currently building an application in Python which receives real-time data through a websocket. Every second my application receives a "tick" from the websocket with data.

I want to look at this tick-data and check the timestamp (UNIX format). The application should ignore most of these ticks but every 6th hour it should run a specific method. (So, if the timestamp is 00:00, 06:00, 12:00 or 18:00 it should run a method.)

I know that timestamp % 3600 checks if it's a whole hour. I tried timestamp % (3600*6) to check for every 6th hour. Unfortuantly this didn't work because it would also trigger false positives.

My question now is, how do i check if a timestamp is a 6th hour? (00:00, 06:00 ,12:00 or 18:00) Here's my current code:

tickertime = tickerdata['E']

        if (tickertime % (3600*6) == 0):
            run_this_method()

Preferably i'm looking for a simple lightweight solution which doesn't take too much complicated datetime conversions, formatting etc. (This because i receive a tick every second so the check should be super fast and efficient.)

I would love to hear if someone knows a smart solution to this. Thanks in advance!

Max

M.vankekeren
  • 115
  • 1
  • 6
  • "Unfortuantly this didn't work because it would also trigger false positives." How so? Testing some samples for `tickertime` seem to work well with this criteria. – MisterMiyagi Mar 28 '22 at 15:04
  • Re: avoiding datetime conversions because you "receive a tick every second so the check should be super fast and efficient", it's worth noting that "every second" is pretty slow. Parsing a datetime object from a timestamp takes on the order of nanoseconds on my system (you can test for yourself with `python3 -m timeit --setup "from datetime import datetime" "datetime.fromtimestamp(datetime.now().timestamp())"`). It's quite likely that absolute efficiency here isn't as important as you might expect – Brian61354270 Mar 28 '22 at 15:10
  • @MisterMiyagi, thanks for the quick reply. Yes so that was what i thought as well until i received the timestamp: 1648409097600 (27-03-2022 19:24:57 GTM) which triggert a false positive because 1648409097600 % (3600*6) = 0 – M.vankekeren Mar 28 '22 at 15:12
  • @M.vankekeren That looks like a *mili*second timestamp. You need to calculate `1648409097600 % (3600*6*1000)` for it. – MisterMiyagi Mar 28 '22 at 15:39

1 Answers1

-1

Store the start time and check if the current time is larger than start + 6 hours. Everytime the check returns True, add 6 hours. If it has to be exactly 0 6 12 and so on, convert to a datetime object and check the hour value directly.

if time.localtime().tm_hour % 6 == 0:
    print(time.localtime().tm_hour)
Michael
  • 104
  • 4