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.
Cet exercice fait partie du cours
Financial Forecasting in Python
Instructions
- Create a variable
dtwhich 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
dtstring by the character/and assign values to theday,monthandyearvariables. - Print the results by concatenating a string using the dictionary for the given month into the new format.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de 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(____ + ' ' + ____[____] + ' ' + ____)