如何在BigQuery SQL中从纪元时间中提取日期

时间:2015-06-06 16:12:22

标签: sql google-bigquery

  1. 我将日期存储在namespace Acme\PhotoBundle\EventListener; use Oneup\UploaderBundle\Event\PostPersistEvent; use Acme\PhotoBundle\Entity\Photo; use Symfony\Component\HttpFoundation\Response; class UploadListener { protected $manager; public function __construct($doctrine) { $this->manager = $doctrine; } public function onUpload(PostPersistEvent $event) { $file = $event->getFile(); $response = $event->getRequest(); $object = new Photo(); $object->setOriginal($file->getPathName()); var_dump($response);enter code here //$this->manager->persist($object); //$this->manager->flush(); } } 中,我想提取 Epoch Time来自它。我尝试了下面的代码,得到Date作为输出。

    null

    Ex time格式(1424184621000000)

  2. 还有一个问题。下面的代码给我正确的日子,但不是工作日,它给了我所有的日子, 是否有可能在Epoch时间内存储两次工作日?

    date_add( (timestamp( Hp.ASSIGN_TIME)), 1970-01-01,"second" ) as Extracted_date_Epoch
    

3 个答案:

答案 0 :(得分:19)

要将timestamp转换为date,您可以使用BigQuery date/time functions

SELECT TIMESTAMP(1424184621000000)       # 2015-02-17 14:50:21 UTC  
SELECT DATE(TIMESTAMP(1424184621000000)) # 2015-02-17   
SELECT DATE(TIMESTAMP('2015-02-17'))     # 2015-02-17   
SELECT INTEGER(TIMESTAMP('2015-02-17'))  # 1424131200000000

要计算两个日期之间的天数(例如2015年6月1日至2015年6月20日),您可以这样做:

SELECT (DATEDIFF(TIMESTAMP('2015-06-20'), TIMESTAMP('2015-06-01')) + 1)

最后计算工作日,您可以使用以下内容:

SELECT
   (DATEDIFF(TIMESTAMP('2015-06-20'), TIMESTAMP('2015-06-01')) + 1)
  -(INTEGER((DATEDIFF(TIMESTAMP('2015-06-20'), TIMESTAMP('2015-06-01')) + 1) / 7) * 2)
  -(CASE WHEN DAYOFWEEK(TIMESTAMP('2015-06-01')) = 1 THEN 1 ELSE 0 END)
  -(CASE WHEN DAYOFWEEK(TIMESTAMP('2015-06-20')) = 7 THEN 1 ELSE 0 END)

这是简单的工作日计算,将周六和周日视为周末,不涉及任何假期。

答案 1 :(得分:18)

如果您在BigQuery中使用standardSQL方言,则此函数会转换为人类可读的时间戳 TIMESTAMP_MICROS(1424184621000000) - > 2015-02-17 14:50:21 UTC 参考: https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#timestamp-string

替代TIMESTAMP_SECONDS(visitStartTime)秒,例如在Google Analytics中。

答案 2 :(得分:0)

如果您有Legacy SQL选项,则回答问题1, 给出一个UNIX纪元时间列,以毫秒为单位,如1524375336000,

我用过 SELECT USEC_TO_TIMESTAMP(Hp.ASSIGN_TIME * 1000) AS the_date FROM table;

╔═══╦═══════════════╦═════════════════════════════╗
║   ║ ASSIGN_TIME   ║ the_date                    ║
╠═══╬═══════════════╬═════════════════════════════╣
║ 1 ║ 1524375336000 ║ 2018-04-22 05:35:36.000 UTC ║
╚═══╩═══════════════╩═════════════════════════════╝
  

USEC_TO_TIMESTAMP(<expr>)将UNIX时间戳(以微秒为单位)转换为   TIMESTAMP数据类型。

     

示例

     

SELECT USEC_TO_TIMESTAMP(1349053323000000);

https://cloud.google.com/bigquery/docs/reference/legacy-sql#usec_to_timestamp