Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading Zero when extract Day and Month

Tags:

postgresql

Hello i'm trying to extract current day and month in a query. This query is filling table from csv file. the file is named like this:

LOG_01_01_2018.csv

My query search for file:

LOG_1_1_2018.csv

With no Zero in front day and month. How to add Zero numbers?

Here is the code:

 execute format ($f$COPY tmp_x FROM 'D:\Programs\PS\download_files_from_ftp_avtomat\files\LOG_%s_%s_%s.csv' 
(header, FORMAT CSV, DELIMITER ',', NULL ' ', ENCODING 'WIN1251');
$f$,extract(day from now()),extract(month from now()),extract(year from now()));
like image 939
Hristian Yordanov Avatar asked Jan 19 '18 09:01

Hristian Yordanov


1 Answers

One option uses LPAD:

execute format ($f$COPY tmp_x FROM 'D:\Programs\PS\download_files_from_ftp_avtomat\files\LOG_%s_%s_%s.csv'
(header, FORMAT CSV, DELIMITER ',', NULL ' ', ENCODING 'WIN1251');
$f$,
    lpad(extract(day from now())::text, 2, '0'),
    lpad(extract(month from now())::text, 2, '0'),
    extract(year from now()));

The year would always be a fixed width four digit number, unless you plan to work with data which existed before computers were around.

like image 171
Tim Biegeleisen Avatar answered Nov 15 '22 17:11

Tim Biegeleisen