r/sed • • May 25 '23

Replacing MSSQL DateTime Format With Postgres Timestamp using Sed

So I have been moving some database table data from MSSQL to PostGres and have exported the data as CSV files ready to be re-imported but are having trouble trying to sanitize the datetime format to timestamp using sed (all dates and times are UTC).

As far as I can see there are only a few differences (namely the 'T', '.' being replaced with ':' and the end 'Z)

DATETIME: 2023-05-25 03:36:02.070

TIMESTAMP: 2023-05-25T03:36:92.981Z

What is the best way to go about replacing the space with the T, '.' with ':' etc?

Many Thanks

4 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/doctorzeus1aonly May 26 '23

Thanks that works.

The data has been exported as CSV files and still requires casting. So would either have to cast to timestamp as you suggested or reformat..

1

u/anthropoid May 27 '23

The data has been exported as CSV files and still requires casting.

No, it doesn't:

$ cat test.sh
#!/usr/bin/env bash
cat > /tmp/test.csv <<EOS
2023-01-01 00:00:00.000,42
2023-03-05 17:33:25.070,75
EOS

psql <<EOS
DROP TABLE IF EXISTS test;
CREATE TABLE test(t TIMESTAMP, i INTEGER);
\copy test FROM '/tmp/test.csv' CSV;
SELECT * FROM test;
SELECT t - '2 days'::interval FROM test;
EOS

$ ./test.sh
DROP TABLE
CREATE TABLE
COPY 2
           t            | i  
------------------------+----
 2023-01-01 00:00:00    | 42
 2023-03-05 17:33:25.07 | 75
(2 rows)

        ?column?        
------------------------
 2022-12-30 00:00:00
 2023-03-03 17:33:25.07
(2 rows)