[英]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()
版本。
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.