【问题标题】:Get datetime interval in postgreSQL在 postgreSQL 中获取日期时间间隔
【发布时间】:2021-06-18 21:15:18
【问题描述】:

我想从 postgresql 查询中获取特定的时间间隔日期时间。例如,当前日期时间是“2021-03-21”,然后我想在“3”月的“1”天从这个日期时间获取指定的时间间隔,以及到 1 年前的时间间隔,所以它得到“2020-02 -01"

区间“2020-02-01”到“2021-03-01”

这是我的代码行

and date_post >= date_trunc('month', '2021-03-01'-interval '1' year)
and date_post < date_trunc('month', '2021-02-01')

但我收到一条错误消息:

 ERROR: invalid input syntax for type interval: "2021-03-01"

【问题讨论】:

  • 试试:'2021-03-01'-interval '1 year' ;)

标签: python sql postgresql datetime


【解决方案1】:

试试这个:

and date_post >= date_trunc('month',  CAST('2021-03-01' AS timestamp) - '1 year'::interval)
and date_post < date_trunc('month', CAST('2021-02-01'AS timestamp))

您可以使用 date() 函数将时间戳转换为日期。

【讨论】:

  • 我认为日期是互换的,因为你说:间隔“2020-02-01”到“2021-03-01”。
  • 请记住 date_trunc() 函数截断到指定的精度,在你的情况下是月份。
【解决方案2】:

使用date 引入日期常量:

date_post >= date_trunc('month', date '2021-03-01' - interval '1' year) and
date_post < date_trunc('month', date '2021-02-01')

当然,您提供的值不需要date_trunc()

如果您使用值作为字符串构造查询,则可以改用::date 转换字符串:

date_post >= date_trunc('month', '2021-03-01'::date - interval '1' year) and
date_post < date_trunc('month', '2021-02-01'::date)

【讨论】:

    【解决方案3】:

    获取时间戳字段,大于 PostgreSQL 中的日期:

    SELECT * from table-name
    WHERE your-timestamp > to_date('05 jan 2020', 'DD Mon YYYY');
    

    您还可以从 PostgreSQL 中的时间戳中减去小时、年、分钟:

    SELECT * from table-name
    WHERE your-timestamp >now()- interval '1 year 2 day';
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-11-28
      • 2011-11-11
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 2012-05-06
      • 1970-01-01
      相关资源
      最近更新 更多