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)
相关推荐
专注API从业者9 分钟前
Open Claw 京东商品监控选品实战:一键抓取、实时监控、高效选品
java·服务器·数据库
大迪deblog13 分钟前
系统架构师-数据库-数据库设计
数据库·oracle·系统架构
leo__52025 分钟前
IEC 104 协议 C 语言实现
c语言·数据库
摇滚侠26 分钟前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
若兰幽竹1 小时前
【从零开始编写数据库系统:架构设计与实现】第5章:查询执行引擎与火山模型
数据库·架构·数据库内核·toydb
天空属于哈夫克31 小时前
企业微信API常见的错误和解决方案
java·数据库·企业微信
东风破1372 小时前
DM8达梦数据库备份、恢复原理介绍
数据库·oracle·dm达梦数据库
鹏子训2 小时前
AI记忆新思路:用SQLite替代向量数据库,去EMBEDDINGS化,谷歌开源Google Always On Memory Agent
数据库·人工智能·sqlite·embedding
Frank_refuel2 小时前
终端环境下:Ubuntu 22.04.1 安装 MySQL 数据库
数据库·mysql·ubuntu
虹科网络安全3 小时前
艾体宝产品|深度解读 Redis 8.4 新增功能:原子化 Slot 迁移(下)
数据库·redis·bootstrap