6

I am trying to upload CSV data to a PostgreSQL database in Python using the COPY FROM STDIN function.

In the CSV file my Date field is DD-MM-YYYY HH:MI and this gives me an error:

psycopg2.errors.DatetimeFieldOverflow: date/time field value out of range: "31-12-2020 08:09"

Is there a way I can define the Date/Time format when using COPY FROM?

DB column is type TIMESTAMP if relevant.

I only know how to do this with a line-by-line INSERT statement.

4
  • @S-Man apologies that was just me typing off the top of my head. I am just copying from CSV with no Date format specified, I'll update for correctness. Thanks. Commented Feb 23, 2021 at 15:15
  • Could it be that your database is expecting 2020-12-31 instead of 31-12-2020? You could always import it to a text column and cast it to timestamp afterwards ;-) Would it be an option? Although postgres would cast it withnout any problems: SELECT '31-12-2020 08:09'::timestamp ;-) Commented Feb 23, 2021 at 15:21
  • @JimJones yes I believe PostgreSQL is expecting 2020-12-31 format but I don't know if this can be manipulated with the COPY FROM function. I assume using a temporary text column will still be considerable more efficient than having Python do a line-by-line file read & insert Commented Feb 23, 2021 at 15:29
  • 1
    It is indeed much more efficient to parse and transform data once they are inside of the database. And you're right: using INSERT statements would be terribly inefficient with large files. Commented Feb 23, 2021 at 15:32

1 Answer 1

5

Just before the COPY command do:

set datestyle = euro;

show datestyle;
 DateStyle 
-----------
 ISO, DMY

Then this works:

SELECT '31-12-2020 08:09'::timestamp;
      timestamp      
---------------------
 2020-12-31 08:09:00

Otherwise with my default datestyle:

show datestyle;
 DateStyle 
-----------
 ISO, MDY

SELECT '31-12-2020 08:09'::timestamp;
ERROR:  date/time field value out of range: "31-12-2020 08:09"
LINE 1: SELECT '31-12-2020 08:09'::timestamp;

For more information see here Date input Table 8.15. Date Order Conventions

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

2 Comments

Thanks. I created temporary text columns to get the data loaded then in pgAdmin I used "UPDATE public.my_table SET actual_datetime_col=(SELECT str_datetime_col::timestamp)" to update.
You could save a step by just temporarily changing the datestyle setting in the session before you do the COPY.

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.