1

This is my dataset:

from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()

df = spark.createDataFrame([('2021-02-07',),('2021-02-08',)], ['date']) \
    .select(
        F.col('date').cast('date'),
        F.date_format('date', 'EEEE').alias('weekday'),
        F.dayofweek('date').alias('weekday_number')
    )
df.show()
#+----------+-------+--------------+
#|      date|weekday|weekday_number|
#+----------+-------+--------------+
#|2021-02-07| Sunday|             1|
#|2021-02-08| Monday|             2|
#+----------+-------+--------------+

dayofweek returns weekday numbers which start on Sunday.

Desired result:

+----------+-------+--------------+
|      date|weekday|weekday_number|
+----------+-------+--------------+
|2021-02-07| Sunday|             7|
|2021-02-08| Monday|             1|
+----------+-------+--------------+
ZygD
  • 22,092
  • 39
  • 79
  • 102

2 Answers2

2

You can try this :

date_format(col("date"), "u")).alias('weekday_number')

For some reason, it's not in the Spark's documentation of datetime patterns for formatting

You also might need to add this configuration line:
spark.conf.set('spark.sql.legacy.timeParserPolicy', 'LEGACY')

Thanks for your feedback and very happy to help =)

Christophe
  • 651
  • 4
  • 22
  • I have upvoted, but I cannot accept the answer, because of two reasons. 1. Using Spark 3+ I am forced to use "LEGACY" configuration which is likely to be discontinued later. 2. In my real case, I already use "spark.sql.legacy.timeParserPolicy" configuration, but with another value, so I cannot use both configurations at the same time... – ZygD Dec 01 '21 at 13:53
  • No problem, the most important is that it helps =) – Christophe Dec 01 '21 at 16:31
0
F.expr('weekday(date) + 1')

weekday

from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.getOrCreate()

df = spark.createDataFrame([('2021-02-07',),('2021-02-08',)], ['date']) \
    .select(
        F.col('date').cast('date'),
        F.date_format('date', 'EEEE').alias('weekday'),
        F.expr('weekday(date) + 1').alias('weekday_number'),
    )
df.show()
#+----------+-------+--------------+
#|      date|weekday|weekday_number|
#+----------+-------+--------------+
#|2021-02-07| Sunday|             7|
#|2021-02-08| Monday|             1|
#+----------+-------+--------------+
ZygD
  • 22,092
  • 39
  • 79
  • 102