How to add a variable number of hours to a date in PostgreSQL?
To add hours to a timestamp in PostgreSQL, use:
In this code your_date
is your timestamp, and hours_to_add
is the number of hours you want to add. No extra operations necessary here, straight to the future!
Understanding data types
When using the +
operator with interval data type, the resulting data type depends on your_date
. If your_date
is a timestamp, the result is a timestamp. If your_date
is a date, the result will be a timestamp without the time zone. Always use numerical values for hours_to_add
to avoid runtime errors.
Dealing with fractional hours
In case you need to add non-integer hours, say 1.5 hours, use either of these:
The latter approach assumes hours_to_add
as a floating point number, thus permitting fractional hours.
Shorthand notation
To make your code shorter and more readable, use shorthand "1 hour" to "1h".
This approach improves query readability when you have multiple interval calculations.
Handling complex cases
Working with non-standard intervals
Adding a variable interval which doesn't fit whole hours needs some creativity. Use make_interval
function:
For fractional hours, convert to minutes:
Dealing with time zones
If you are adding hours to a timestamp with time zone
, the output reflects the UTC equivalent. Convert the timezone appropriately before addition for local time operations.
Common traps and shortcuts
Evading timestamp overflow
Adding astronomical hours might hit PostgreSQL's timestamp limit. Always validate your input to prevent a journey to the end of time.
Ensuring precision
Floating point arithmetic can cause minute inaccuracies. Use integer values or cast to numeric if precision is important and hours can be fractional.
Working with DST
Manipulating timestamp with time zone
might cause pitfalls during Daylight Saving Time shifts. Use AT TIME ZONE to normalize these changes.
Was this article helpful?