xo / usql

Universal command-line interface for SQL databases
MIT License
8.94k stars 352 forks source link

How can i control the datetime format when i export data to csv file #327

Closed kilik52 closed 2 years ago

kilik52 commented 2 years ago

When export data to csv from clickhouse database, the datetime string are like:YYYY-MM-DDTHH:mm:ssZ.

How can i format the date like YYYY-MM-DD HH:mm:ss?

kenshaw commented 2 years ago

I don't recall specifically if dates from the Clickhouse database driver are coming back as actual time.Time types. If they aren't, then the formatting option available in usql won't work. You can set a time formatting option using \pset time Kitchen:

$ usql pg://
Connected with driver postgres (PostgreSQL 14.2 (Debian 14.2-1.pgdg110+1))
Type "help" for help.

pg:postgres@=> select now();
             now             
-----------------------------
 2022-04-16T22:05:22.572256Z 
(1 row)

pg:postgres@=> \pset time Kitchen
Time display is "Kitchen" ("3:04PM").
pg:postgres@=> select now();
   now   
---------
 10:05PM 
(1 row)

pg:postgres@=>  

The above is documented in the README.md. It uses Go's time constants, so you're able to do things like this:

pg:postgres@=> \pset time 2006-01-02
Time display is "2006-01-02" ("2006-01-02").
pg:postgres@=> select now()
pg:postgres@-> ;
    now     
------------
 2022-04-16 
(1 row)

pg:postgres@=> 

Please try setting the time format and executing a query using usql.

I'm not that familiar with Clickhouse's SQL functionality, but alternately I would suggest using Clickhouse's SQL formatting functions if the Clickhouse database has that capability. Should that fail you, I'd suggest using something like awk after generating csv output to modify the displayed values.