【问题标题】:extract week number from date postgres从日期 postgres 中提取周数
【发布时间】:2016-03-07 03:05:33
【问题描述】:

我想提取周数为:

2015-52

从格式如下的日期开始:

2015-12-27

如何在 postgres 中执行此操作?

我的周数是从星期一到星期日计算的。

【问题讨论】:

    标签: time postgresql-9.1


    【解决方案1】:

    要以单个字符值获取年份和星期,请使用to_char()

    select to_char(current_date, 'IYYY-IW');
    

    IW 返回年份和周数,defined in the ISO standardIYYY 返回相应的年份(可能是前一年)。

    如果您需要年份和周数作为数字,请使用extract

    select extract('isoyear' from current_date) as year, 
           extract('week' from current_date) as week;
    

    【讨论】:

    • @Feenaboccles:对。当使用IW 时,还需要使用等值年IYYY - 我会解决这个问题
    • 哇,修改一个 3 年前的答案做得很好:) 我没想到会有回应,只是想留下一些东西让下一个人看到这个页面?
    【解决方案2】:

    我已经这样做了

    extract(week from cast(current_date as date))
    extract(year from cast(current_date as date))
    

    【讨论】:

    • 表达式cast(current_date as date)可以简化为current_date
    【解决方案3】:

    与@a_horse_with_no_name 相同,但要注意extract('isoyear' from current_date)extract('year' from current_date) 之间有一点区别,如果current_date 在新年的第0 周内(去年的最后一周(53)),尤其是当你也提取week

    例如:

    以下输出是2020 而不是2021

    select EXTRACT('isoyear' from to_timestamp('2021-01-02 17:37:27', 'YYYY-MM-DD hh24:mn:ss')) as year
    

    下面的输出是2021

    select EXTRACT('year' from to_timestamp('2021-01-02 17:37:27', 'YYYY-MM-DD hh24:mn:ss')) as year
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多