I have a query that unfortunately has to compare 2 timestamps. One timestamp is given to the DB from the PHP date() function, stored as timestamp without time zone, so there’s no milliseconds added to this date. The other is a PG timestamp with time zone. So both dates have already been created and inserted into the tables, here is an example of the dates:
timestamp without time zone = 2012-09-19 18:13:26
PG’s timestamp with time zone = 2012-09-19 18:13:26.893878-04
I can cast the PG date::timestamp(0) which gets me close but as would be expected the date is rounded up; 2012-09-19 18:13:27
So my question is how can I get the seconds to round down?
Comparing timestamps for equality is rarely going to work well. What if the two timestamps were taken at
2012-09-19 18:13:26.99999999? Clock jitter, scheduler jitter, execution time differences, etc could and often will push one over into the next second. It doesn’t have to be that close to the edge to happen, either. You can try hacks withCompare with a tight range instead; say 2 seconds:
I’m not sure you can use anything coarser than that because the precision of your PHP timestamp is 1 second.
If you know for sure that PHP always truncates the timestamp (rounds down) rather than rounding to even when it captures the timestamp, you can roughly correct for this by adjusting the bracketing intervals. Eg to attempt a 1 second interval (the narrowest you can test for given your timestamp precision from PHP) try, and assuming PHP always truncates the timestamp down:
Personally I’d add at least another 0.1 second each side to be sure:
If you really insist on testing for equality, use:
but be aware it’s dangerous and wrong to test two separately captured timestamps for equality.