简体   繁体   English

如何将“ 01MAR1978:00:00:00”字符串格式的日期转换为SparkR中的日期格式?

[英]How to Convert Date in “01MAR1978:00:00:00” string format to Date Format in SparkR?

I have dates in the following formats: 我的日期具有以下格式:

  1. 08MAR1978:00:00:00 08MAR1978:00:00:00
  2. 10FEB1973:00:00:00 10FEB1973:00:00:00
  3. 15AUG1982:00:00:00 15AUG1982:00:00:00

I would like to convert them to: 我想将它们转换为:

  1. 1978-03-08 1978-03-08
  2. 1973-02-10 1973-02-10
  3. 1982-09-15 1982-09-15

I have tried the following in SparkR: 我在SparkR中尝试了以下方法:

period_uts <- unix_timestamp(all.new$DATE_OF_BIRTH, '%d%b%Y:%H:%M:%S')
period_ts <- cast(period_uts, 'timestamp')
period_dt <- cast(period_ts, 'date')
df <- withColumn(all.new, 'p_dt', period_dt)    

But when I do this, all the dates get changed into "NA". 但是,当我这样做时,所有日期都变成了“ NA”。

Can anyone please provide some insights on how I can convert dates in %d%B%Y:%H:%M:%S format to dates in SparkR? 谁能提供一些见解,说明如何将%d%B%Y:%H:%M:%S格式的日期转换为SparkR中的日期?

Thanks! 谢谢!

I don't think you need SparkR to solve this question. 我认为您不需要SparkR即可解决此问题。

What you have: 你有什么:

DoB <- c("08MAR1978:00:00:00", "10FEB1973:00:00:00", "15AUG1982:00:00:00")

If you want to get 1978-03-08 etc. you could just use as.Date in combination with the date format you already found yourself: 如果您想获取1978-03-08等,可以将as.Date与已经发现的日期格式结合使用:

as.Date(DoB, format="%d%B%Y:%H:%M:%S")
# [1] "1978-03-08" "1973-02-10" "1982-08-15"

as.Date will ensure that R knows how to interpret your string as a date. as.Date将确保R知道如何将您的字符串解释为日期。

Note, however, that in general the way dates are displayed to you (ie 1978-03-08) actually don't really matter. 但是请注意,通常,日期显示给您的方式(即1978-03-08)实际上并不重要。 The reason is that 'under the hood', R understands your date now, so all date-related operations will be performed appropriately. 原因是,“ R幕后” R现在了解您的日期,因此所有与日期有关的操作都将适当执行。

I figured out how to do it: 我想出了办法:

all.new = all.new %>% withColumn("Date_of_Birth_Fixed", to_date(.$DATE_OF_BIRTH,  "ddMMMyyyy"))

This works in Spark 2.2.x 这适用于Spark 2.2.x

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

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