I’m trying to change the format of time_discrep (below) into a fraction of days.
Code:
select time1, time2, (time1-time2) as time_discrep
from main_file
order by time1;
I’ve tried dividing, etc, but it just formats it like 00:00:32 and things like that.
UPDATE: I found something that works, but I don’t know if it’s the best way:
4
Answers
Convert to seconds using
extract(epoch from ...)
then use arithmetic to get days as a decimal by dividing by the number of seconds in a day:The basic math is days + (hours / 24) + (minutes / (24 * 60)) + (seconds / (24 * 60 * 60)). We can write a little function to do the conversion from an interval to a numeric.
A date minus a date give you the number of days between these two dates:
This also works when you have a much larger number of days, like months or years.
interval
usingExtract()
.epoch
from just the::time
part to turn hours and minutes to seconds in one move, then divide that by one day.+
.demo at db<>fiddle
The
::numeric(7,2)
cast is just to make it look nice – skip that if you prefer higher precision.Feels nice to have the code work similar to how you’d perform the operation mentally, but it can all be shortened to a single
extract
:Which turns out is pretty much what @Bohemian had suggested already.
If you’re generating the
interval
by taking a difference between timestamps, it comes out justified. If you’re working with raw intervals, remember to usejustify_interval()
before extracting anything butepoch
, otherwise:Even though the hours amount to 2 more days, they get ignored. Justifying fixes that: