从Postgres的日期提取工作日,毫秒,微秒,纳秒

时间:2017-05-29 11:07:19

标签: sql postgresql datepart

如何从Postgres中的日期中提取毫秒,工作日,微秒,纳秒。我也尝试了提取方法,但是我找不到完全相同的方法。

3 个答案:

答案 0 :(得分:2)

据我所知,Postgres不支持纳秒。其余的:

select extract(dow from timestamp '2001-02-16 20:38:40.5');
| date_part |
| :-------- |
| 5         |
select extract(milliseconds from timestamp '2001-02-16 20:38:40.5');
| date_part |
| :-------- |
| 40500     |
select extract(microseconds from timestamp '2001-02-16 20:38:40.5');
| date_part |
| :-------- |
| 40500000  |

dbfiddle here

答案 1 :(得分:1)

https://www.postgresql.org/docs/current/static/datatype-datetime.html,请查看“表8 - 9。日期/时间类型”日期类型解析 1天。所以你不能得到上述任何一个,但工作日:

var cells: [MessageCell] = [.from(""), .to(""), .subject(""), .to("")]

let recipient = "John"

for case let (offset, .to) in cells.enumerated() {
    cells[offset] = .to(recipient)
    break
}

print(cells) 
// [MessageCell.from(""), MessageCell.to("John"),
//  MessageCell.subject(""), MessageCell.to("")]

如果您要查找日期缩写,而不是星期日:

t=# select extract(Dow from now()::date);
 date_part
-----------
         1
(1 row)

答案 2 :(得分:1)

我不确定你要找的是什么,但是:

    PostgreSQL中的
  • there is no nanosecond precision对于timestampinterval类型,p (精度)的允许范围为0到6。< / em>的
  • 某些日期部分包含其他内容:即milliseconds包含seconds&amp; microseconds包含milliseconds(因此也seconds)。

如果您正在寻找逻辑上独立的值,您需要做一些数学运算,例如:

select extract(dow from ts) dow,       -- day-of-week (where weeks start on sunday, which is 0)
       extract(isodow from ts) isodow, -- ISO day-of-week (where weeks start on monday, which is 1)
       floor(extract(seconds from ts))::int only_seconds,
       floor(extract(milliseconds from ts))::int - 1000 * floor(extract(seconds from ts))::int only_milliseconds,
       floor(extract(microseconds from ts))::int - 1000 * floor(extract(milliseconds from ts))::int only_microseconds,
       extract(microseconds from ts) all_microseconds

或者,如果您正在查看时间戳在其实际周内的距离,您也可以使用timestamp(和interval)算术:

select ts - date_trunc('week', ts) time_elapsed_since_monday

(虽然很难计算周日开始的周数:date_trunc仅适用于ISO周)。

http://rextester.com/SOOO48159