clickhouseSQL日期相关

1. 毫秒级时间戳转日期/小时

sql 复制代码
--13位时间戳转具体时间
toDateTime(report_time / 1000) as _c00 

-- 获取时间戳对应的时间点整点(结果:%Y-%m-%d %H:00:00.0) eg:2022-09-28 23:00:00.0
toStartOfHour(toDateTime(report_time / 1000)) AS _10

-- 获取时间点整点(结果无日期:%H)eg:23
toHour(FROM_UNIXTIME(report_time div 1000)) as _100

-- 13位时间戳转成年月日时(结果:%Y-%m-%d %H)
FROM_UNIXTIME(report_time div 1000,'%Y-%m-%d %H') 


-- 获取时间戳对应的日期开始时间(结果:%Y-%m-%d 00:00:00.0)eg:2022-09-28 00:00:00.0
toStartOfDay(toDateTime(report_time / 1000)) AS _02

--获取时间戳对应的日期(结果:%Y-%m-%d)eg:2022-09-28
toDate(toDateTime(report_time / 1000)) AS _01
toDate(toStartOfDay(toDateTime(report_time / 1000))) AS _0

-- 获取n分钟间隔(eg,10分钟间隔指00-09,10-19......55-59)
toStartOfInterval(toDateTime(report_time / 1000), INTERVAL 10  minute)

-- 字符串时间转datetime
toDateTime('2023-02-02 01:02:15')

结果如下:

● "/"和"div"的区别

"/"非整除,结果仍然是浮点数

"div"为整除,得到10位数结果

2. 当前时间往前推

解决凌晨0点之后,例行时间是跑前一日23点数据的问题

sql 复制代码
-- 获取当前时间
now()

-- 当前时间前推1小时
date_sub(hour, 1, now())

-- 再转换为日期
toDate(date_sub(hour, 1, now()))

-- 前推n天
date_sub(day,7,toDate(date_sub(hour,1,now())))--前推7天

-- 当前时间往前推1小时,并转化为int8格式
toInt8(substring(cast(date_sub(hour, 1, toDateTime('2023-02-02 01:02:15')) as String), 12, 2))
toInt8(substring(CAST(minus(toDateTime('2023-02-02 01:02:15'), toIntervalHour(1)), 'String'), 12, 2))
-- toDateTime('2023-02-02 01:02:15') = now()
相关推荐
童谣11 小时前
越华环保集团市级统筹申报数字化中台:政策校验与减排仿真一体化架构
数据库·架构
制造数据与AI践行者老蒋1 小时前
离谱!PromptTemplate 遇上 JSON,花括号直接引发解析战争
数据库·microsoft·json
中微极客1 小时前
用LangChain 0.3构建生产级RAG与Agent:从API集成到Streamlit部署
数据库·人工智能·langchain
吴声子夜歌1 小时前
MongoDB 4.x——并发优化
数据库·mongodb
不如语冰2 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
提笔了无痕3 小时前
MySQL SQL 从 EXPLAIN 到索引优化,搞懂 SQL 为什么慢
android·sql·mysql
l1t4 小时前
DeepSeek总结的DuckLake 架构深度剖析-2
数据库·架构
YOU OU5 小时前
Redis事务
数据库·redis·缓存
辰同学ovo5 小时前
从一条 SQL 到三个原则:MySQL 心智模型
sql·mysql·adb
数智化管理手记5 小时前
财务大数据怎么管住资金风险?财务大数据和财务数智化到底怎么结合?
大数据·网络·数据库·人工智能·数据挖掘