How to convert Unix epoch time in SQLite
Asked Answered
S

3

60

Could you help me convert UNIX epoch time into format yyyy-mm-dd hh:mm:ss (24h) in SQLite? (GMT+7 would be appreciated).

Example: from 1319017136629 to Wednesday, October 19, 2011 4:38:56 PM GMT+7.

p/s: Just looked around and found a solution:

SELECT datetime(1319017136629, 'unixepoch', 'localtime');

But i am still looking for a way to batch convert UNIX epoch time in SQLite.

Seif answered 31/1, 2013 at 15:33 Comment(2)
Store in the database in UTC, display to the user in their local time. To do anything else is just asking for troubleBathhouse
@Petesh how is Epoch timestamp aka Unix time "asking for trouble"?Beefwood
B
44

1319017136629 is a value in milliseconds, which is not UNIX epoch time; therefore it has to be divided by 1000 and rounded to integer seconds; only then DATE() and DATETIME() will convert.

SELECT DATETIME(ROUND(dateColumn / 1000), 'unixepoch') AS isodate FROM tableName

Converting database values to localtime is unfortunate; conversion on output is less problematic.

The Y2038 problem might already be worth a consideration.

Bohlin answered 14/1, 2019 at 2:3 Comment(0)
D
38

To change the values in the database, use the UPDATE command:

UPDATE MyTable SET MyColumn = datetime(MyColumn, 'unixepoch', 'localtime')
Diluent answered 31/1, 2013 at 16:21 Comment(2)
Problem solved. I had to convert sqlite db to mysql. In mysql i have more advanced query: UPDATE yourtable SET yourcolumn = from_unixtime(yourcolumn)Seif
Remember to NOT directly convert INT (for unix timestamps) to DATETIME, you have to first change it to VARCHAR, convert it with above UPDATE statement and then convert it to DATETIME. Alternative is to add another column of DATETIME, convert old -> new column directly, delete old column and rename new back to old column.Tiaratibbetts
H
6

Same as stated above:

SELECT DATE(ROUND(1601272453000 / 1000), 'unixepoch')

Hoke answered 20/10, 2020 at 12:45 Comment(1)
Can you explain?Jun

© 2022 - 2024 — McMap. All rights reserved.