【问题标题】:TypeError: TimestampType can not accept object <class 'str'> and <class 'int'>TypeError: TimestampType 不能接受对象 <class 'str'> 和 <class 'int'>
【发布时间】:2019-11-30 16:00:37
【问题描述】:

我有一个要写入 HDFS 表的 pandas 数据框。当Srum_Entry_CreationStringType() 时,我可以将数据写入表,但我需要它为TimestampType()。这就是我遇到TypeError: TimestampType can not accept object '2019-05-20 12:03:00' in type &lt;class 'str'&gt;TypeError: TimestampType can not accept object 1558353780000000000 in type &lt;class 'int'&gt; 的地方。在定义架构之前,我尝试在 python 中将列转换为不同的日期格式,但似乎可以让导入工作。

df
    Srum_Entry_ID   Connected_Time  Machine     Srum_Entry_Creation
0   5769.0          0.018218        Computer1   2019-05-20 12:03:00
1   5770.0          0.000359        Computer1   2019-05-20 12:03:00
2   5771.0          0.042674        Computer2   2019-05-20 13:03:00
3   5772.0          0.043229        Computer2   2019-05-20 14:04:00
4   5773.0          0.032222        Computer3   2019-05-20 14:04:00

spark = SparkSession.builder.appName('application').getOrCreate()
schema = StructType([StructField('Srum_Entry_ID', FloatType(), False),
                     StructField('Connected_Time', FloatType(), True),
                     StructField('Machine', StringType(), True),
                     StructField('Srum_Entry_Creation', TimestampType(), True)])
dataframe = spark.createDataFrame(df, schema)
dataframe.write. \
  mode("append"). \
  option("path", "/user/hive/warehouse/analytics.db/srum_network_connections"). \
  saveAsTable("analytics.srum_network_connections")

我试过了:

df['Srum_Entry_Creation'] = df['Srum_Entry_Creation'].astype('datetime64[ns]')

错误: TypeError: TimestampType can not accept object 1558353780000000000 in type &lt;class 'int'&gt;

df['Srum_Entry_Creation'] = pd.to_datetime(df['Srum_Entry_Creation'])

错误: TypeError: TimestampType can not accept object 1558353780000000000 in type &lt;class 'int'&gt;

如果我只是将它作为字符串留在熊猫数据框中,我会得到:

错误:TypeError: TimestampType can not accept object '2019-05-20 12:03:00' in type &lt;class 'str'&gt;

【问题讨论】:

  • 你试过用日期时间格式替换它吗?
  • 我试过 df['Srum_Entry_Creation'] = df['Srum_Entry_Creation'].astype('datetime64[ns]') 和 df['Srum_Entry_Creation'] = pd.to_datetime(df['Srum_Entry_Creation '])
  • 还有什么错误?一样吗?
  • 我将它们添加到@Steven 的问题中
  • 这是一个选项,将时间戳作为字符串从 spark 导出并稍后转换?我知道这有点痛,因为这意味着额外的转换,但如果它有效?!或者是否可以使用numpy.datetime64 代替TimestampType(),因为似乎用作TimestampType 的类不能转换为熊猫使用恕我直言的numpy.timestamp64

标签: python pandas pyspark apache-spark-sql


【解决方案1】:

简而言之,我将日期时间转换为纪元时间

df['epoch'] = (df['New_Srum_Entry_Creation'] - dt.datetime(1970,1,1)).dt.total_seconds()
df['epoch'] = df['epoch'].astype('Int64')

然后将 IntegerType() 用于架构

StructField('epoch', IntegerType(),True)

【讨论】:

  • 这并没有真正回答原来的问题。
猜你喜欢
  • 2021-12-05
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 2011-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多