简体   繁体   English

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

[英]how to get hour, month from timestamp in postgresql

timestamp with timezone is this - 2020-05-31T10:05:07Z带有时区的时间戳是 - 2020-05-31T10:05:07Z

this is not working, despite referencing official documentation.尽管参考了官方文档,但这不起作用。 I need to extract may 2020 or separate month and year to compare against May 2020我需要提取 2020 年 5 月或单独的月份和年份以与 2020 年 5 月进行比较

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


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

If you want to check if a timestamp value is "may 2020", you have different options.如果要检查时间戳值是否为“2020 年 5 月”,您有不同的选择。

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

or或者

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

or或者

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

extract() and date_part() are the same thing - but I prefer the standard compliant extract() version. extract()date_part()是一回事——但我更喜欢标准兼容的extract()版本。

demo:db<>fiddle 演示:db<>小提琴

You need to_char() to format a date or timestamp.您需要to_char()来格式化日期或时间戳。 Mon gives you the first three letters of a month name: Mon为您提供月份名称的前三个字母:

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

Returning the entire month name you can use Month instead of Mon .返回整个月份名称,您可以使用Month而不是Mon But, for some reasons, the length of the Month value is fixed to the longest month name available.但是,由于某些原因, Month值的长度固定为可用的最长月份名称。 That means May is returned with right padded spaces.这意味着May返回右填充空格。 To avoid this, you need to add the modifier FM :为避免这种情况,您需要添加修饰符FM

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从时间戳列 postgresql 获取月份名称 - get month name from timestamp column postgresql 如何从 1 小时时间戳表中以更高的日期分辨率(4 小时、1 天、1 周、1 个月 - 每小时、每天。每月)获取 Postgres 记录 - How to get Postgres records in higher date resolution (4 hours, 1 day, 1 week, 1 month - hourly, daily. monthly) from 1 hour timestamp table PostgreSQL:从时间戳截断小时/分钟/秒 - PostgreSQL: truncate hour/min/second from a timestamp PostgreSQL中距时间戳的小时以进行动态查询 - hour from timestamp in postgresql for dynamic queries Postgresql - 如何修复时间戳中的无效小时? - Postgresql - How to fix invalid hour in timestamp? 在 PostgreSQL 中获取一个月前的时间戳 - Get timestamp of one month ago in PostgreSQL Postgresql - 如何将一个时间戳转换为另一个时间戳与更接近的时间? - Postgresql - How to convert one timestamp to another timestamp with its closer hour? 在PostgreSQL中,如何获取按月在x轴上按小时分组和按小时在y轴上分组的计数表? - How can I get a table of counts grouped by month on axis x and by hour on axis y in PostgreSQL? 使用PostgreSQL从Unix时间戳中提取日期,月份,年份和月份名称 - Extract date,month,year and month name from the unix timestamp with postgresql 按小时间隔加入 postgresql 时间戳 - Join postgresql timestamp on hour interval
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM