【问题标题】:how to get hour, month from timestamp in postgresql如何从postgresql中的时间戳获取小时,月
【发布时间】:2021-02-17 13:32:28
【问题描述】:

带有时区的时间戳是这个 - 2020-05-31T10:05:07Z

这不起作用,尽管参考了官方文档。我需要提取 2020 年 5 月或单独的月份和年份以与 2020 年 5 月进行比较

SELECT date_trunc('hour', TIMESTAMP '2020-05-31T10:05:07Z')


SELECT date_part('day', TIMESTAMP '2020-05-31T10:05:07Z');

【问题讨论】:

  • 好吧,date_TRUNC 不提取任何东西 - 请定义“不工作”。您对第一个陈述和第二个陈述有何期望?
  • date_part('day') 送出 31。你期待什么?
  • 你想对小时部分做什么?

标签: postgresql timestamp


【解决方案1】:

如果您想检查时间戳值是否为“2020 年 5 月”,您有不同的选择。

 to_char(the_value, 'yyyy-mm') = '2020-05'

    extract(month from the_value) = 5 
and extract(year from the_value) = 2020 

(extract(month from the_value), extract(year from the_value)) = (5, 2020)

extract()date_part() 是一回事 - 但我更喜欢符合标准的 extract() 版本。

【讨论】:

    【解决方案2】:

    demo:db<>fiddle

    您需要to_char() 来格式化日期或时间戳。 Mon 为您提供月份名称的前三个字母:

    SELECT
        to_char(
            TIMESTAMP '2020-05-31T10:05:07Z',
            'Mon YYYY'
        )
    

    返回整个月份名称,您可以使用Month 代替Mon。但是,由于某些原因,Month 值的长度固定为可用的最长月份名称。这意味着 May 返回右填充空格。为避免这种情况,您需要添加修饰符FM

    SELECT
        to_char(
            TIMESTAMP '2020-05-31T10:05:07Z',
            'FMMonth YYYY'
        )
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 2013-11-06
      • 1970-01-01
      • 2012-06-29
      • 2011-11-11
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      相关资源
      最近更新 更多