DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Datafaker: An Alternative to Using Production Data
  • High-Performance Java Serialization to Different Formats
  • RION - A Fast, Compact, Versatile Data Format
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Trending

  • How the Go Runtime Preempts Goroutines for Efficient Concurrency
  • Streamlining Event Data in Event-Driven Ansible
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)
  • What Is Plagiarism? How to Avoid It and Cite Sources
  1. DZone
  2. Data Engineering
  3. Data
  4. Apache Spark: Reading CSV Using Custom Timestamp Format

Apache Spark: Reading CSV Using Custom Timestamp Format

Here's the solution to a timestamp format issue that occurs when reading CSV in Spark for both Spark versions 2.0.1 or newer and for Spark versions 2.0.0 or older.

By 
Jyotsna  Karan user avatar
Jyotsna Karan
·
Jun. 07, 17 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
28.6K Views

Join the DZone community and get the full member experience.

Join For Free

In this blog, we are considering a situation where I wanted to read a CSV through Spark, but the CSV contains some timestamp columns in it. Is this going to be a problem while inferring schema at the time of reading the CSV using spark?

Well, the answer may be no if the CSV has the timestamp field in the specific yyyy-MM-dd hh:mm:ss format. In this particular case, the spark CSV reader can infer it to timestamp considering it as the default format.

id,name,age,joining_date,wedding_date
1,Joseph,25,1999-09-04 45:50:46,2014-11-22 00:00:00
val csvDataFrame = session.sqlContext.read.format("com.databricks.spark.csv")
.option("header", "true")
.option("treatEmptyValuesAsNulls", "true")
.option("inferSchema", "true")
.option("mode","DROPMALFORMED")
.load("<path of the csv file>")

csvDataframe.printSchema()

When you read the schema of the DataFrame after reading the CSV, you will see that every field has been inferred correctly by the CSV.

root
 |-- id: integer (nullable = true)
 |-- name: string (nullable = true)
 |-- age: integer (nullable = true)
 |-- joining_date: timestamp (nullable = true)
 |-- wedding_date: timestamp (nullable = true)

But what if the timestamp fields in the CSV are in some other timestamp format? (For example, MM-dd-yyyy hh mm ss format.)

The content of the CSV file will be:

id,name,age,joining_date,wedding_date
1,Joseph,25,09-04-1999 45 50 46,11-22-2014 00 00 00

In this case, Spark does not get the timestamp field. It will not be able to infer the CSV field/column correctly considering that column to be of string type.

When you see a DataFrame schema this time, it will give the timestamp field as a string:

root
 |-- id: integer (nullable = true)
 |-- name: string (nullable = true)
 |-- age: integer (nullable = true)
 |-- joining_date: string (nullable = true)
 |-- wedding_date: string (nullable = true)

The above-mentioned issues have a solution depending on the version of Spark we are using.

Solution 1: Using Spark Version 2.0.1 and Above

Here, you have the straight-forward option timestampFormat to give any timestamp format while reading CSV. We have to just add an extra option defining the custom timestamp format, like option(“timestampFormat”, “MM-dd-yyyy hh mm ss”).

val csvDataframe = session.sqlContext.read.format("com.databricks.spark.csv") .option("header", "true")
.option("treatEmptyValuesAsNulls", "true")
.option("inferSchema", "true")
.option("mode", "DROPMALFORMED")
.option("timestampFormat", "MM-dd-yyyy hh mm ss")
.load("<path of the csv file>")

csvDataframe.printSchema()

In this way, you will have the timestamp field correctly inferred when we even have some other timestamp format in the CSV file.

root
|-- id: integer (nullable = true)
|-- name: string (nullable = true)
|-- age: integer (nullable = true)
|-- joining_date: timestamp (nullable = true)
|-- wedding_date: timestamp (nullable = true)

Remember: This solution will work only in Spark versions greater than 2.0.0 (2.0.1 and above). If you have Spark version 2.0.0 or older, check out Solution 2 with a workaround.

Solution 2: Using Spark Version 2.0.0 or Older

In older versions of Spark, the above option for timestampFormat does not exist, though we have the way to do so. Let it be inferred as a string, and cast the string field having the timestamp value explicitly to the timestamp.

For this, you must know the columns that need to be converted to the timestamp.

For example, I know all my timestamp fields end with _date. Then those fields can be explicitly cast to any timestamp format.

val csvDataframe = session.sqlContext.read.format("com.databricks.spark.csv")
.option("header", "true")
.option("treatEmptyValuesAsNulls", "true")
.option("inferSchema", "true")
.option("mode", "DROPMALFORMED")
.load("<path of the csv file>")

val updatedDF = csvDataframe.columns.filter(colName =>colName.endsWith("_date"))
.foldLeft(csvDataframe) { (outputDF, columnName) =>
outputDF.withColumn(columnName, unix_timestamp(col(columnName), "MM-dd-yyyy hh mm ss").cast("timestamp"))
}
updatedDF. printSchema ()

This way, you will able to get the correct data type for timestamp fields with other formats, as well.

root
|-- id: integer (nullable = true)
|-- name: string (nullable = true)
|-- age: integer (nullable = true)
|-- joining_date: timestamp (nullable = true)
|-- wedding_date: timestamp (nullable = true)

Conclusion

While you read CSV using Spark, you may have problems while reading timestamp field having timestamp format other than the default one, i.e yyyy-MM-dd hh:mm:ss. This blog has the solution to this timestamp format issue that occurs when reading CSV in Spark for both Spark versions 2.0.1 or newer and for Spark versions 2.0.0 or older. 

CSV file IO Data Types

Published at DZone with permission of Jyotsna Karan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Datafaker: An Alternative to Using Production Data
  • High-Performance Java Serialization to Different Formats
  • RION - A Fast, Compact, Versatile Data Format
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!