How to truncate date in postgres? - postgresql

I am using below condition to truncate date in postgres
to_date(to_char(trunc(appointment_date),'YYYYMMDD')||appointment_end_time,''YYYYMMDDHH24:MI:SS')AS tq
How I can use this in postgres ?

Strange data typing, sometimes requires strange, looking at least, queries. Try (see fiddle)
date_trunc('day',appointment_date)
+ substr(appoinment_end,12)::interval

As your to_char() call uses the format 'HH24:MI:SS' for the "time" column, you can cast that column directly to a time value, e.g. using the :: operator: appointment_end_time::time.
To build a new timestamp from the date part of the appointment_date and the time value, just add them:
appointment_date::date + appointment_end_time::time
So first the timestamp is converted to a date (that does not have a time), and then the time value is added to that, which yields a timestamp.
Note that to_date() returns a date so your code would remove the just added time part again. You would need to use to_timestamp() if you really want a timestamp as the result.
To answer the question's title "how to truncate date in Postgres?" (which in reality refers to a timestamp not a date): you can either cast it to a date (see above) or you can use date_trunc() (not trunc()) with a unit to which it should be truncated. However, date_trunc returns a timestamp not a date value, so you couldn't add a time to the result.

Related

What is the best way to store formatted timestamp in Postgresql

What is the best way to store a timestamp value in Postgresql in a specific format.
For example I would like to store a TIMESTAMP '2020-07-09 17:29:30.873513Z' down to the minute and ignore seconds value.
I can drop the seconds by using date_trunc('minute', TIMESTAMP '2020-07-09 17:29:30.873513Z') Is there anyway for me to specify this format in the column itself when I create a table?
Don't store formatted timestamps in the database, use timestamp with time zone or timestamp without time zone. You would lose powerful datetime arithmetic, value checking and waste storage space.
To have the values truncated to minute precision, use a BEFORE INSERT trigger that uses date_trunc on the value.
If you want to ascertain that only such values are stored, add a check constraint.
I would like to recommend not to drop seconds or anything from the stored data. Because it will create issues while you process the data later. And if you have to eliminate anything, you may eliminate it while retrieving the data.
Use the following code while creation of table
col_name timestamp without time zone DEFAULT timezone('gmt'::text, now())
This will give you a result as shown in the following image:
Good Luck.

postgreSQL increment number in output

I am extracting three values (server, region, max(date)) from my postgresql> But I want to extract an additional 4th field which should be the numerical addition of 1 to 3rd field. I am unable to use date add function as in the database date field is defined as an integer.
date type in DB
date|integer|not null
tried using cast and date add function
MAX(s.date)::date + cast('1 day' as interval)
Error Received
ERROR: cannot cast type integer to date
Required output
select server, region, max(alarm_date), next date from table .....
testserver, europe, 20190901, 20190902
testserver2, europe, 20191001, 20191002
next date value should be the addition to alarm_date
To convert an integer like 20190901 to a date, use something like
to_date(CAST(s.date AS text), 'YYYYMMDD')
It is a bad idea to store dates as integers like that. Using the date data type will prevent corrupted data from entering the database, and it will make all operations natural.
First solution that came to my mind:
select (20190901::varchar)::date + 1
Which output 2019-09-02 as type date.
Other solutions can be found here.

Converting long (numbers) text datatype (with blank values) to date

I have troubles converting HubSpot UNIX timestamp to date. Timestamp is stored as text value.
Value looks like this:
1549324800000
My logic was first to convert the number to bigint and later converted it to date using:
TO_CHAR(TO_TIMESTAMP(properties__vape_station__value)), 'DD/MM/YYYY')
What would be the best way to achieve converting UNIX Timestamp in text type to date in PostgreSQL 11.
You can cast the value in that column to a bigint and then use to_timestamp.
But apparently that column also stores empty strings rather than NULL values if no value is present, so you need to take that into account:
to_timestamp(nullif(trim(properties__vape_station__value),'')::bigint/1000)
This would still fail however if anything else than a number is stored in that column.

Converting string timestamp into date

I have dates in a postgres database. The problem is they are stored in a string field and have values similar to: "1187222400000" (which would correspond to 07.08.2007).
I would like to convert them into readable dates usind some SQL to_date() expression or something similar but can't come up with the correct syntax to make it work.
There really isn't enough information here for a conclusion, so I propose this 'scientific-wild-ass-guess' to resolve your puzzle. :)
It appears this number is UNIX 'epoch time' in milliseconds. I'll show this example as if your string field had the arbitrary name, 'epoch_milli'. In postgresql you can convert it to a time stamp using this statement:
SELECT TIMESTAMP WITH TIME ZONE 'epoch' + epoch_milli * INTERVAL '1 millisecond';
or using this built-in postgresql function:
SELECT to_timestamp(epoch_milli / 1000)
either of which, for the example '1187222400000', produces the result
"2007-08-15 17:00:00-07"
You can do some of your own sleuthing with quite a few values selected similarly to this:
SELECT to_timestamp(epoch_milli/1000)::DATE
FROM (VALUES (1187222400000),(1194122400000)) AS val(epoch_milli);
"Well, bollocks, man. I just want the date." Point taken.
Simply cast the timestamp to a date to discard the excess bits:
SELECT to_timestamp(epoch_milli / 1000)::DATE
Of course its possible that this value is a conversion or is relative to some other value, hence the request for a second example data point.

Is ISO8601 the best date-format for PostgreSQL jsonb when i want to filter by the date?

I'm new to PostgreSQL and I have the following question:
I have a table with just an id-column and a data-column, which uses the jsonb-type. Inside the jsonb-object I have a datetime field. I read in various posts, that I should use the ISO-8601 dateformat to store in the DB.
I want to filter my table by date like this:
SELECT * FROM table WHERE data->'date' > '2016-01-01T00:00'
Is this really the best date-format for this purpose?
Thanks in advance :)
IMHO Your query should produce
ERROR: operator does not exist: jsonb > timestamp with time zone
If I get it right. In case you change -> to ->> it should get a text value instead of jsonb field (which is also not comparable to timestamp).
It should be smth like
SELECT * FROM table WHERE (data->>'date')::timestamptz > '2016-01-01T00:00' to work
The big advantage of that format is that string order corresponds to date order, so a comparison like the one you quote in your question would actually work as intended.
A second advantage is that a timestamp in that format can easily be converted to a PostgreSQL timestamp with time zone value, because the type input function understands this format.
I hope you are not dealing with dates “before Christ”, because it wouldn't work so easily with those.