对postgresql日期和时间的比较
作者:安達と島村
文章介绍了在数据库中处理日期和时间类型时的一些注意事项,包括如何将字符串转换为日期或时间类型,以及在比较时自动转换的情况,作者建议在使用数据库时,根据具体情况进行适当的类型转换,以避免潜在的错误
postgresql日期和时间比较
DB里保存到时分秒,需要和年月日比较
select date_trunc('day',now())=date_trunc('day',date('20200615')) --true select date_trunc('day',date('20200611')) --2020-06-11 00:00:00+00 select * from users where date_trunc('day',birthday)=date_trunc('day',date('20200401'))
db里存储date或者timestamp字段
需要和字符串比较时,建议先使用to_date或者to_timestamp转换。
测试发现pgsql往类型为timestamp的列插入字符串数据,或者用date/timestamp类型的数据跟字符串数据作比较时,会自动转换成对应的date/timestamp。
oracle未测试。
select to_date('2019-01-15 18:33:41','yyyy-MM-dd hh24:mi:ss'); select to_timestamp('2019-01-15 18:33:41','yyyy-MM-dd hh24:mi:ss');
select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')= to_timestamp('2019-01-15 00:00:00','yyyy-MM-dd hh24:mi:ss'); >>true select to_timestamp('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')- to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss'); >>"18:33:42" select to_timestamp('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01/15'; >>false select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01/15'; >>true select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019-01-15'; >>true select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='20190115'; >>true select to_date('2019-01-15 18:33:42','yyyy-MM-dd hh24:mi:ss')='2019/01-15'; >>ERROR: date型の入力構文が不正です: "2019/01-15" SELECT time, to_timestamp('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'), time=to_timestamp('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'), time,to_date('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss'), time=to_date('2011-12-13 14:15:16','yyyy-MM-dd hh24:mi:ss') FROM public.product where id =21; >>"2011-12-13 14:15:16+09" >>"2011-12-13 14:15:16+09" >>true >>"2011-12-13 14:15:16+09" >>"2011-12-13" >>false
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。