pg_sql关于时间的函数

1、时间戳和日期之间的相互转换

时间戳转日期(时间戳为数值类型,若为字符型需进行转换)

复制代码
# 保留到秒:2025-10-02 04:46:40 (字符型转换数值型)
select to_timestamp('1759351600'::bigint)

# 保留到日:2025-10-02
select date(to_timestamp(1759351600))

# 自定义格式:2025/10/02
to_char(to_timestamp(1759351600),'YYYY/mm/dd')

2、interval

作用:实现时间日期的加减

格式:日期 +/- interval '加减值'

复制代码
# 前一天
select current_date - interval '1 day'

# 后一周
select current_date + interval '1 week'

# 前一月
select current_date - interval '1 month'

# 后一年
select current_date + interval '1 year'

3、date_trunc

作用:获取日期对应参数的起始

格式:date_trunc(('参数',日期))

复制代码
# 获取年第一天
select date_trunc('year',now())

# 获取年最后一天(获取下一年的第一天后减一天)
select date_trunc('year',now() + interval '1 year') - interval '1 day'

# 获取季第一天
select date_trunc('quarter',now())

# 获取季最后一天
select date_trunc('quarter',now() + interval '3 month') - interval '1 day'

# 获取月第一天
select date_trunc('month',now())

# 获取月最后一天
select date_trunc('month',now() + interval '1 month') - interval '1 day'

# 获取周第一天
select date_trunc('week',now())

# 获取周最后一天
select date_trunc('week',now() + interval '1 week') - interval '1 day'

计算类:

剩余时间

复制代码
# 周
select date_trunc('week',now() + interval '1 week') - now()

# 月
select date_trunc('month',now() + interval '1 month') - now()

# 季
select date_trunc('quarter',now() + interval '3 month') - now()

# 年
select date_trunc('year',now() + interval '1 year') - now()

剩余天数

复制代码
# 周
select date_trunc('week',current_date + interval '1 week') - interval '1 day' - current_date 

# 月
select date_trunc('month',current_date  + interval '1 month') - interval '1 day' - current_date 

# 季
select date_trunc('quarter',current_date  + interval '3 month') - interval '1 day' - current_date 

# 年
select date_trunc('year',current_date  + interval '1 year') - interval '1 day' - current_date 

4、date_part

作用:获取日期对应的参数是当前年的第几(周、月、季)

格式:date_part('参数',日期)

复制代码
# 获取当前时间是第几天
select date_part('day',now())

# 获取当前时间是第几周
select date_part('week',now())

# 获取当前时间是第几月
select date_part('month',now())

# 获取当前时间是第几季
select date_part('quarter',now())

5.extract

作用:提取时间中某些内容(可以实现和date_part类似功能)

格式:extract(提取值from时间)

复制代码
# 天
select extract(day from current_date)

# 月
select extract(month from current_date)

# 年
select extract(year from current_date)

# 周
select extract(week from current_date)

# 季
select extract(quarter from current_date)
相关推荐
小虾米vivian2 分钟前
dmetl5 web管理平台 监控-流程监控 看不到运行信息
linux·服务器·网络·数据库·达梦数据库
yuzhucu8 分钟前
django4.1.2+xadmin配置
数据库·sqlite
「光与松果」12 分钟前
MySQL中统计各个IP的连接数
数据库·mysql
骄傲的心别枯萎13 分钟前
RV1126 NO.57:ROCKX+RV1126人脸识别推流项目之读取人脸图片并把特征值保存到sqlite3数据库
数据库·opencv·计算机视觉·sqlite·音视频·rv1126
boy快快长大23 分钟前
【MySQL】InnoDB记录存储结构
数据库·mysql
yaoxtao24 分钟前
neo4j数据库的导入和导出
数据库
卓码软件测评27 分钟前
CMA/CNAS软件测评机构:【Gatling数据库性能关联测试JDBC连接和SQL执行时间监控】
数据库·sql·测试工具·性能优化·测试用例
lixora33 分钟前
备份指定oracle block 防止误操作
数据库
凯子坚持 c40 分钟前
Redis 数据库的服务器部署与 MCP 智能化交互深度实践指南
服务器·数据库·redis
DBA小马哥1 小时前
Oracle迁移金仓全攻略:工业IOT场景下的易用性与安全保障
数据库·物联网·安全·oracle