Problem

Table: Days

1
2
3
4
5
6
+-------------+------+
| Column Name | Type |
+-------------+------+
| day         | date |
+-------------+------+
day is the column with unique values for this table.

Write a solution to convert each date in Days into a string formatted as "day_name, month_name day, year".

Return the result table in any order.

The result format is in the following example.

Examples

Example 1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
Input: 
Days table:
+------------+
| day        |
+------------+
| 2022-04-12 |
| 2021-08-09 |
| 2020-06-26 |
+------------+
Output: 
+-------------------------+
| day                     |
+-------------------------+
| Tuesday, April 12, 2022 |
| Monday, August 9, 2021  |
| Friday, June 26, 2020   |
+-------------------------+
Explanation: Please note that the output is case-sensitive.

Solution

Method 1 – Date Formatting in SQL and Pandas

Intuition

We need to convert a date to a string in the format “day_name, month_name day, year”. SQL and Pandas both provide date formatting functions to achieve this.

Approach

  1. Use SQL date formatting functions to extract the day name, month name, day, and year from the date.
  2. Concatenate these parts into the required format.
  3. In Pandas, use the dt.strftime method to format the date column.

Code

1
2
3
SELECT 
  DATE_FORMAT(day, '%W, %M %e, %Y') AS formatted_date
FROM Days;
1
2
3
SELECT 
  TO_CHAR(day, 'FMDay, FMMonth FMDD, YYYY') AS formatted_date
FROM Days;
1
2
3
4
def convert_date_format(df: 'pd.DataFrame') -> 'pd.DataFrame':
    df = df.copy()
    df['formatted_date'] = df['day'].dt.strftime('%A, %B %-d, %Y')
    return df[['formatted_date']]

Complexity

  • ⏰ Time complexity: O(n), where n is the number of rows in the Days table.
  • 🧺 Space complexity: O(n), for storing the result set.