将字符串插入timestamp(6)列

时间:2019-11-25 14:53:01

标签: oracle scala apache-spark timestamp

我有这样的时间戳:2019-06-13 13:22:30.521000000

我正在使用Spark / Scala脚本将它们插入到Oracle表中。 Oracle中的列是Timestamp(6),应该保持这样。

这就是我要做的:

我在Spark中拥有的是一个df,其中包含带有我的时间戳的列:

+-----------------------------+
|   time                      |
+-----------------------------+
|2019-06-13 13:22:30.521000000| 
+-----------------------------+

我执行以下操作:

df.withColumn("time", (unix_timestamp(substring(col("time"), 1, 23), "yyyy-MM-dd HH:mm:ss.SSS") + substring(col("time"), -6, 6).cast("float") / 1000000).cast(TimestampType))

,然后使用与Oracle的连接来插入(插入脚本已经过测试,可以正常工作)。 但是在Oracle中,我只在表中看到以下内容:

+--------------------------+
|   time                   |
+--------------------------+
|2019-06-13 13:22:30.000000| 
+--------------------------+

不包括毫秒。有什么帮助吗?谢谢!

3 个答案:

答案 0 :(得分:0)

如果您的time列是时间戳类型,则可以尝试date_format

https://sparkbyexamples.com/spark/spark-sql-how-to-convert-date-to-string-format/

答案 1 :(得分:0)

我不知道您使用的工具是什么,但是-如果只是Oracle,那么to_timestamp带有适当的格式掩码就可以完成任务。看看是否有帮助。

SQL> create table test (col timestamp(6));

Table created.

SQL> insert into test (col) values
  2    (to_timestamp('2019-06-13 13:22:30.521000000', 'yyyy-mm-dd hh24:mi:ss.ff'));

1 row created.

SQL> select * From test;

COL
---------------------------------------------------------------------------
13.06.19 13:22:30,521000

SQL>

[编辑,因为您看不懂我的想法(至少希望如此)

正如您(AbderrahmenM)所说的那样,您有一个字符串,但仍想插入一个时间戳,也许您可​​以使用存储过程。这是一个示例:

SQL> create or replace procedure p_test (par_time in varchar2)
  2  is
  3  begin
  4    insert into test (col) values
  5      (to_timestamp(par_time, 'yyyy-mm-dd hh24:mi:ss.ff'));
  6  end;
  7  /

Procedure created.

SQL> exec p_test('2019-06-13 13:22:30.521000000');

PL/SQL procedure successfully completed.

SQL> select * from test;

COL
-------------------------------------------------------------------
13.06.19 13:22:30,521000

SQL>

现在,我唯一无法帮助的是如何从Spark调用过程。如果您知道怎么做,那么只需传递您拥有的字符串,然后将其正确插入数据库即可;注意正确的格式掩码!

答案 2 :(得分:0)

我感谢所有试图帮助我的人。

这是我要获得所需输出的方法:

df.withColumn("time", (unix_timestamp(substring(col("time"), 1, 23), "yyyy-MM-dd HH:mm:ss.SSS") + substring(col("time"), -9, 9).cast("float") / 1000000000).cast(TimestampType))

所有其他解决方案始终以毫秒为单位返回null或时间戳。

希望它可以帮助某人。