[英]Presto SQL date_format extract week of year
文档: https://prestodb.io/docs/current/functions/datetime.html
我有纪元时间戳,我想从中提取一年中的一周,例如2021-32
、 2020-50
、 2021-02
等等。
SELECT concat(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%Y'),
'-' ,
date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%v'))
AS week
但是我得到了一些错误的值,例如:星期 = 2021-53
对应于 2021 年 1 月 1 日或 2021 年 1 月 2 日的纪元时间。我知道这里发生了同步问题,但这绝对不是我想要的 -我如何抵消,以便第 1 周的第一天从年初开始。
在这种情况下,您应该只计算天数并计算周数。 像这样的东西:
SELECT concat(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%Y'),
'-' ,
ceiling(date_format(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000), '%j')/7))
AS week
这里没有同步问题 - 它是date_format
的预期行为,它是 MySQL 对应物。
请注意,您可以在日期上使用完整格式的字符串:
select date_format(timestamp '2021-01-01', '%Y-%v')
_col0 |
---|
2021-53 |
我能够使用week_of_year
和year_of_week
方法解决它。
文档: https://prestodb.io/docs/current/functions/datetime.html#week
询问:
SELECT concat(CAST(year_of_week(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000)) AS varchar(15)),
'-',
CAST(week_of_year(from_unixtime((CAST(my_timestamp AS BIGINT) + 19800000)/1000)) AS varchar(15))) as week
由于 concat 不支持多种数据类型,因此不得不向 varchar 引入一些额外的强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.