Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a timestamp (DATE FORMAT) to BIGINT in SQL

Tags:

sql

I need to convert the timestamp value (Format: 2012-11-19 14:29:50.0) to a BIGINT value (Format: 2012111315041650 = YYYYMMDDhhmmss). I need to insert current time in a column of a table which accepts only BIGINT.

I am using Squirrel SQL Client Version 3.3.0. The query I am using right now is

INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE) 
VALUES (2012111315041650, CURRENT_TIMESTAMP); 

Instead of manually entering the BIGINT_DATE value, I want to convert the CURRENT_TIMESTAMP or NOW() to a BIGINT value as the format YYYYMMDDHHMISS

Something like

INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE) 
VALUES ("CONVERT(CURRENT_TIMESTAMP,BIGINT)", CURRENT_TIMESTAMP); 

Let me know if it is feasible to do this way

Please help me with this.

Thanks

like image 399
developer1 Avatar asked Nov 20 '12 16:11

developer1


People also ask

How do I change the format of a timestamp in SQL?

select to_char(sysdate, 'YYYY-MM-DD') from dual; To get this format by default, set it in your session's NLS_DATE_FORMAT parameter: alter session set NLS_DATE_FORMAT = 'YYYY-MM-DD'; You can also set the NLS_TIMESTAMP_FORMAT and NLS_TIMESTAMP_TZ_FORMAT .

How do I convert a timestamp to a date in SQL?

CAST() function performs the same way as CONVERT(), i.e. it too converts the value of any data type in the desired data type. Thus, we can make use of this function to convert the retrieved current timestamp in the date and time values.

Can we cast decimal to Bigint?

Casting between DECIMAL and other data types:You can cast DECIMAL to the following types: FLOAT , TINYINT , SMALLINT , INT , BIGINT , STRING , BOOLEAN , TIMESTAMP.


2 Answers

For Postgres you can use:

INSERT INTO table1 (BINGINT_DATE, TIMESTAMP_DATE) 
VALUES (to_char(current_timestamp, 'yyyymmddhh24miss')::bigint, CURRENT_TIMESTAMP); 
like image 121
a_horse_with_no_name Avatar answered Sep 23 '22 23:09

a_horse_with_no_name


To convert timestamp values to bigint values (in seconds) you can do it in this way:

SELECT (EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::bigint -- -> 1554216999

To convert timestamp values to bigint values (in millis) you can do it in this way:

SELECT ((EXTRACT(EPOCH FROM TIMESTAMP '2019-04-02T14:56:39.009'))::numeric * 1000)::bigint -- -> 1554216999009

If you want to convert all timestamp values of a column into a table into another column of the same table you can run this query (result in millis):

UPDATE $table_name$ SET $column_with_values_bigint$ = (EXTRACT(EPOCH FROM $column_with_values_timestamp$)::numeric * 1000)::bigint

Hope this help.

like image 45
Manuel Avatar answered Sep 24 '22 23:09

Manuel