1

How can I get SQLite to convert excel-type serial numbers to dates, e.g. I want the integer 40074 in a table to somehow get the date 18-Sept-2009?

The dates are already in SQLite.

5 Answers 5

3
sqlite> SELECT DATE('1899-12-30', '+40074 days');
2009-09-18
3

This seems to work:

sqlite> SELECT DATETIME((49400 * 3600 * 24) - 3014928000, 'unixepoch');
2009-09-18 00:00:00

Honestly, I just guess and checked on the constant there, but I'm sure there's simple math to back it up.

It looks like it works for dates earlier than the epoch as well, but I haven't tested it thoroughly.

0

Excel stores dates as the number of days since 30-Dec-1899 so to convert a number to/from a date, you simply have to calculate the number of days between 30-Dec-1899 and the date you're after. How you do that depends on exactly which language you're working in, but for C# for example, the following would work:

var epoch = new DateTime(1899, 12, 30);

int number = 40074;
var date = epoch.AddDays(number);
Console.WriteLine(date);

var date = new DateTime(1987, 5, 3);
int number = (int) date.Subtract(epoch).TotalDays;
Console.WriteLine(number);

(If you're wondering why the epoch is 30/12/1899, it's because the actual epoch is supposed to be 1/1/1900 but Excel erroneously assumes that 1900 was a leap year)

3
  • Sorry, I specifically asked about working in SQLite. I have no problem understanding the system or working in other languages (python being my favourite).
    – John Smith
    May 5, 2010 at 2:33
  • 1
    The same principle applies; it's just the syntax that's different.
    – dan04
    May 5, 2010 at 6:45
  • 1
    Actually it was Lotus 123 that used 1/1/1900 as epoch while erroneously assuming 1900 to be a leap year. For Excel (VBScript) they corrected this by putting the epoch date back. For all dates after februari 29 1900 both Excel and Lotus 123 agree, for the dates before they differ (but Excel is right there in fact). Mar 8, 2011 at 12:10
0

To handle excel date value and return human-readable date in sqlite3 consider:

-- unix epoch is 00:00:00 UTC on 1 January 1970 (1970/01/01)

-- 86400 = Seconds in a day

-- 25569 = Days between 1970/01/01 and 1900/01/01 (min date in Windows Excel)

The formula, or statement rather:

SELECT DATETIME(( EXCEL_DATE - 25569) * 86400 , 'unixepoch') AS UNIX_DATE;

Example completed from excel date provided in the initial question:

sqlite> SELECT DATETIME(( 40074 - 25569) * 86400 , 'unixepoch') AS UNIX_DATE;

2009-09-18 00:00:00
0
0

Thanks @Aman_Srivastava it worked very well

alter mytable add fixed_date DATE;

update mytable set fixed_date = DATE(( excel_date - 25569) * 86400 , 'unixepoch') where excel_date is not null;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.