Converting date formats - explicit
Let's have a look at one of the dates from the previous exercise.
- Sale A: 4000 on 14/02/2018
We used the datetime
library to identify the day d
, month m
, and year y
which could help us to identify data from datasets with different date formats. However, what about a scenario where we want to convert date formats into a specific format?
In this exercise you will convert Sale A from the format 14/02/2018 to the same date format as Sale B (i.e. 14 February 2018).
We can do this easily with built-in Python functions. Remember, to split a string we can use the .split()
method.
The input for this exercise will be the datetime of Sale A.
This exercise is part of the course
Financial Forecasting in Python
Exercise instructions
- Create a variable
dt
which contains a string representation of the date you want to convert to a new format (i.e. Sale A). - Create a dictionary for the months
mm
, which will specify which month corresponds to which number, in the format{'number':'month name'}
. - Split the
dt
string by the character/
and assign values to theday
,month
andyear
variables. - Print the results by concatenating a string using the dictionary for the given month into the new format.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Set the variable for the datetime to convert
dt = '____'
# Create the dictionary for the month values
mm = {'01': '____', '____': 'February', '____': '____'}
# Split the dt string into the different parts
____, ____, year = dt.split('____')
# Print the concatenated date string
print(____ + ' ' + ____[____] + ' ' + ____)