如何从postgresql中的时间戳获取小时,月份

时间:2021-02-17 13:32:28

标签: postgresql timestamp

带时区的时间戳是这个 - 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');

2 个答案:

答案 0 :(得分: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() 版本。

答案 1 :(得分:0)

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'
    )
相关问题