如何在DB Browser for SQLite中从mm/dd/yyyy格式日期获取星期几与月份?
SQLite提取日期的月份与星期几(解决TO_DATE报错)
为什么TO_DATE会报错?
SQLite没有内置TO_DATE函数,它的日期处理依赖strftime()、date()等专用函数,且仅支持YYYY-MM-DD这类标准格式的日期解析,所以直接调用TO_DATE会提示函数不存在。
解决方案:先转标准日期格式,再提取信息
你的日期格式是DD/MM/YYYY(含单数字日/月,比如2/4/2018),需要先拆分并拼接成SQLite能识别的YYYY-MM-DD格式,再用strftime()提取月份和星期几。
完整SQL语句
SELECT Date AS original_date, -- 提取两位数字月份(如04、12) strftime('%m', substr(Date, instr(Date, '/', instr(Date, '/') + 1) + 1) || '-' || substr(Date, instr(Date, '/') + 1, instr(Date, '/', instr(Date, '/') + 1) - instr(Date, '/') - 1) || '-' || substr(Date, 1, instr(Date, '/') - 1) ) AS month_number, -- 提取月份全称(如April、December) strftime('%B', substr(Date, instr(Date, '/', instr(Date, '/') + 1) + 1) || '-' || substr(Date, instr(Date, '/') + 1, instr(Date, '/', instr(Date, '/') + 1) - instr(Date, '/') - 1) || '-' || substr(Date, 1, instr(Date, '/') - 1) ) AS month_name, -- 提取星期几数字(0=周日,1=周一…6=周六) strftime('%w', substr(Date, instr(Date, '/', instr(Date, '/') + 1) + 1) || '-' || substr(Date, instr(Date, '/') + 1, instr(Date, '/', instr(Date, '/') + 1) - instr(Date, '/') - 1) || '-' || substr(Date, 1, instr(Date, '/') - 1) ) AS weekday_number, -- 提取星期几全称(如Friday、Sunday) strftime('%A', substr(Date, instr(Date, '/', instr(Date, '/') + 1) + 1) || '-' || substr(Date, instr(Date, '/') + 1, instr(Date, '/', instr(Date, '/') + 1) - instr(Date, '/') - 1) || '-' || substr(Date, 1, instr(Date, '/') - 1) ) AS weekday_name FROM Xtrain;
关键逻辑说明
- 拆分日期:用
instr()定位斜杠位置,不管日/月是1位还是2位,都能准确拆分出年、月、日部分 - 拼接标准格式:将拆分出的年、月、日按
YYYY-MM-DD拼接,让SQLite能解析为日期类型 - 提取信息:通过
strftime()的格式化参数获取需要的信息,常用参数:%m:两位数字月份%B:英文月份全称%w:星期几数字(0=周日)%A:英文星期几全称
如果需要中文的月份/星期几,可以用CASE语句映射,比如:
CASE strftime('%m', substr(Date, instr(Date, '/', instr(Date, '/') + 1) + 1) || '-' || substr(Date, instr(Date, '/') + 1, instr(Date, '/', instr(Date, '/') + 1) - instr(Date, '/') - 1) || '-' || substr(Date, 1, instr(Date, '/') - 1) ) WHEN '01' THEN '一月' WHEN '02' THEN '二月' WHEN '03' THEN '三月' WHEN '04' THEN '四月' WHEN '05' THEN '五月' WHEN '06' THEN '六月' WHEN '07' THEN '七月' WHEN '08' THEN '八月' WHEN '09' THEN '九月' WHEN '10' THEN '十月' WHEN '11' THEN '十一月' WHEN '12' THEN '十二月' END AS month_name_cn
内容的提问来源于stack exchange,提问作者ReidG94
相关产品推荐
相关产品推荐

