简体   繁体   English

Postgresql:如何以十进制小时计算两个日期和时间之间的差异?

[英]Postgresql: How to find difference between 2 dates and times in decimal hours?

System: Postgresql 9.6.系统:PostgreSQL 9.6。 I didn't design this system and this table has startdate (Date type field), starttime (Time), enddate (Date) and endtime (Time) fields but not hours elapsed between the 2. The field types for each field above are in (parens).我没有设计这个系统,这个表有开始日期(日期类型字段)、开始时间(时间)、结束日期(日期)和结束时间(时间)字段,但没有两个字段之间经过的小时数。上面每个字段的字段类型在(括号)。

What I need: using Date and Time fields, I would like the difference in decimal hours.我需要什么:使用日期和时间字段,我想要十进制小时数的差异。 This would be a calculated column in my SELECT statement.这将是我的 SELECT 语句中的计算列。

  1. I've searched a search engine and Stackoverflow for this and there is nothing that exactly matches what I need.我已经为此搜索了搜索引擎和 Stackoverflow,但没有任何内容完全符合我的需要。
  2. Some examples show me the difference in days, but that's now what I want.一些示例向我展示了天数的差异,但这就是我现在想要的。
  3. Other example show only the difference in 2 times, but I need to account for 3rd shift workers that start on one day and end on the next day.其他示例仅显示 2 次的差异,但我需要考虑从一天开始到第二天结束的第 3 班工人。
  4. Other examples do not take into account the different stardate and enddate.其他示例不考虑不同的stardate 和enddate。
  5. Some people may start on one day and finish their shift on the next day so this must take 2 different dates into account.有些人可能从一天开始并在第二天完成他们的轮班,所以这必须考虑 2 个不同的日期。

I tried this and got the result in "hh:mm:ss" format: endtime - starttime as hrs我试过了,得到了“hh:mm:ss”格式的结果: endtime - starttime as hrs

I've been searching a while how to convert that result to decimal hours.我一直在寻找如何将该结果转换为十进制小时数。 I've also tried these formats:我也试过这些格式:

(date enddate time endtime) - (date startdate time starttime) as hrs

(enddate endtime) - (startdate starttime) as hrs

timestamp(enddate endtime) - timestamp(startdate starttime) as hrs

age(enddate endtime) - age(startdate starttime) as hrs

extract(EPOCH FROM timestamptz(enddate endtime)) - extract(EPOCH from timestamptz (startdate starttime))

I don't do much SQL at my job so any help would be appreciated.我在我的工作中没有做太多 SQL,所以任何帮助将不胜感激。 I learn by seeing code but I'd also like to understand what each part does so I can UNDERSTAND and apply that understanding to future issues.我通过查看代码来学习,但我也想了解每个部分的作用,以便我能够理解并将这种理解应用于未来的问题。

Thank you!谢谢!

select extract (EPOCH from (enddate + endtime - (startdate + starttime))) / (60 * 60) from a;

I think this will does what you want:我认为这会做你想要的:

select ((extract(epoch from enddate) + extract(epoch from endtime) -
        (extract(epoch from startdate) + extract(epoch from starttime)
       ) / (60.0 * 60)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM