Postgres按日期计算时区

时间:2017-06-16 03:19:59

标签: postgresql timezone

我想查询一个表,找出Postgres中按日期,日期和月份创建的对象数。

过去30天的抓取次数

SELECT d.date, count(se.id)
FROM (SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD') AS date 
FROM generate_series(0, 30) AS offs) d LEFT OUTER JOIN
     someTable se 
     ON d.date = to_char(date_trunc('day', se.created_at), 'YYYY-MM-DD')  
GROUP BY d.date;

按天获取次数

select to_char(created_at,'day') as Day,
       extract(month from created_at) as Date,
       count("id") as "Count"
from someTable
group by 1,2

按月获取计数

select to_char(created_at,'Mon') as mon,
       extract(year from created_at) as yyyy,
       count("id") as "Count"
from someTable
group by 1,2

这对我来说很好。我遇到的问题是,我希望根据不同的时区获取数据。我已将时间存储在UTC中。我可以用不同的时区运行这些查询。

最好的方法是什么?

1 个答案:

答案 0 :(得分:1)

选中此answer以获取Postgres中具有不同时区的日期时间。

过去30天的抓取次数

SELECT d.date, count(se.id)
FROM (SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD') AS date 
FROM generate_series(0, 30) AS offs) d LEFT OUTER JOIN
     someTable se 
     ON d.date = to_char(date_trunc('day', se.created_at::timestamp with time zone at time zone 'EST'), 'YYYY-MM-DD')  
GROUP BY d.date;

按天获取次数

select to_char(created_at::timestamp with time zone at time zone 'EST','day') as Day,
       extract(month from created_at) as Date,
       count("id") as "Count"
from someTable
group by 1,2

按月获取计数

select to_char(created_at::timestamp with time zone at time zone 'EST','Mon') as mon,
       extract(year from created_at) as yyyy,
       count("id") as "Count"
from someTable
group by 1,2

另请参阅此Postgres documentation以了解有关日期时间的时区。