Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert current_timestamp into Postgres via python

I need to insert rows into PG one of the fields is date and time with time stamp, this is the time of incident, so I can not use --> current_timestamp function of Postgres at the time of insertion, so how can I then insert the time and date which I collected before into pg row in the same format as it would have been created by current_timestamp at that point in time.

like image 431
Max Avatar asked May 16 '11 13:05

Max


People also ask

How do I insert datetime in Python?

To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.

How do I insert current date in Pgadmin?

For current datetime, you can use now() function in postgresql insert query. You can also refer following link. insert statement in postgres for data type timestamp without time zone NOT NULL,.


2 Answers

A timestamp does not have "a format".

The recommended way to deal with timestamps is to use a PreparedStatement where you just pass a placeholder in the SQL and pass a "real" object through the API of your programming language. As I don't know Python, I don't know if it supports PreparedStatements and how the syntax for that would be.

If you want to put a timestamp literal into your generated SQL, you will need to follow some formatting rules when specifying the value (a literal does have a format).

Ivan's method will work, although I'm not 100% sure if it depends on the configuration of the PostgreSQL server.

A configuration (and language) independent solution to specify a timestamp literal is the ANSI SQL standard:

 INSERT INTO some_table   (ts_column)   VALUES   (TIMESTAMP '2011-05-16 15:36:38'); 

Yes, that's the keyword TIMESTAMP followed by a timestamp formatted in ISO style (the TIMESTAMP keyword defines that format)

The other solution would be to use the to_timestamp() function where you can specify the format of the input literal.

 INSERT INTO some_table   (ts_column)   VALUES   (to_timestamp('16-05-2011 15:36:38', 'dd-mm-yyyy hh24:mi:ss')); 
like image 74
a_horse_with_no_name Avatar answered Sep 28 '22 03:09

a_horse_with_no_name


If you use psycopg2 (and possibly some other client library), you can simply pass a Python datetime object as a parameter to a SQL-query:

from datetime import datetime, timezone  dt = datetime.now(timezone.utc) cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,)) 

(This assumes that the timestamp with time zone type is used on the database side.)

More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.

like image 33
Eugene Yarmash Avatar answered Sep 28 '22 03:09

Eugene Yarmash