Reputation: 407
I have date stored in format DD/MM/YYYY HH24:MI TZ
(datetime with timezone) in my psql database. I need to convert this date to a timestamp.
I tried to_timestamp() but it is not working with timezone.
ERROR: "TZ"/"tz"/"OF" format patterns are not supported in to_date
I tried ::timestamptz but it consider date to be in format of MM/DD/YYYY HH24:MI TZ
ERROR: date/time field value out of range
Is there any way to convert the format from DD/MM/YYYY HH24:MI TZ
to MM/DD/YYYY HH24:MI TZ
or convert DD/MM/YYYY HH24:MI TZ
to timestamp?
e.g. "28/04/2017 13:00 +2:30"
Upvotes: 2
Views: 5933
Reputation: 51629
try casting directly?..
so=# select to_timestamp('04/28/2017 13:00 +2:30','D/MM/YYYY HH24:MI TZ');
ERROR: "TZ"/"tz"/"OF" format patterns are not supported in to_date
Time: 20.850 ms
so=# select '04/28/2017 13:00 +2:30'::timestamptz;
timestamptz
------------------------
2017-04-28 10:30:00+00
(1 row)
Time: 0.554 ms
https://www.postgresql.org/docs/current/static/functions-formatting.html
to_timestamp and to_date exist to handle input formats that cannot be converted by simple casting. For most standard date/time formats, simply casting the source string to the required data type works, and is much easier.
update
regarding your comment, you just need to adjust datestyle
to change the parsing:
so=# set datestyle to DMY;
SET
Time: 9.997 ms
so=# select '04/28/2017 13:00 +2:30'::timestamptz;
ERROR: date/time field value out of range: "04/28/2017 13:00 +2:30"
LINE 1: select '04/28/2017 13:00 +2:30'::timestamptz;
^
HINT: Perhaps you need a different "datestyle" setting.
Time: 10.217 ms
so=# set datestyle to MDY;
SET
Time: 8.799 ms
so=# select '04/28/2017 13:00 +2:30'::timestamptz;
timestamptz
------------------------
2017-04-28 10:30:00+00
(1 row)
Upvotes: 2