0

I am trying to format my date column to 'YYYYMM' from 'YYYY-MM-DD'.

My code: SELECT to_char(date '2015-06-01', 'YYYYMM');

I'm not sure if this worked or not because the date still looks like the original format. Also, will the new 'YYYYMM' format be applied to data that is imported in this table?

4
  • Please elaborate your question Commented Nov 11, 2015 at 7:27
  • Take a look at the postgresql documentation for your reference. Commented Nov 11, 2015 at 7:51
  • cast as char, substring etc. Commented Nov 11, 2015 at 8:01
  • No, the data will remain in the correct internal format. Commented Nov 11, 2015 at 8:13

1 Answer 1

2

The date type is implemented as number of days from 2000-01-01 - and this number has not any visual form - it is just the offset. You can change the visualisation, that is used when the data are visualized.

postgres=# set datestyle to ISO;
postgres=# select current_date;
┌────────────┐
│    date    │
╞════════════╡
│ 2015-11-11 │
└────────────┘
(1 row)

postgres=# set datestyle to GERMAN;
postgres=# select current_date;
┌────────────┐
│    date    │
╞════════════╡
│ 11.11.2015 │
└────────────┘
(1 row)

There are other auxiliary functions for formatting date to_char and processing date string to_date. The set of styles available for datestyle is limited. More datestyle is global variable and using it can increase a risk of unwanted defects in application - so the usage of datestyle is not preferred.

postgres=# select to_char(current_date, 'YYYYMM');
┌─────────┐
│ to_char │
╞═════════╡
│ 201511  │
└─────────┘
(1 row)
set datestyle to iso;
postgres=# select to_date('201511','YYYYMM');
┌────────────┐
│  to_date   │
╞════════════╡
│ 2015-11-01 │
└────────────┘
(1 row)

By default the data are communicated from Postgres to client in text format. So the usage of these formatting functions (functionality) has impact on received data (from database) on client side. to_char does explicit convert to text type, so any client can read it (because it have to be able to read text).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.