Aan de slagGa gratis aan de slag

Converting date formats - simple

Sales area A in Europe and Sales area B in Australia have different date formats.

  • Sale A: 4000 on 14/02/2018
  • Sale B: 3000 on 2 March 2018

If we want to consolidate or compare sales periods, we need to convert to the same date format. We can easily do this by using the datetime library and the datetime.strptime(date_string, format) method, using the following directives:

Directive Meaning Example
%d Day of the month as a zero-padded decimal number 01, 02, …, 31
%b Month as locale’s abbreviated name Jan, Feb, …, Dec
%B Month as locale’s full name January, …, December
%m Month as a zero-padded decimal number 01, 02, …, 12
%y Year without century as a zero-padded decimal number 00, 01, …, 99
%Y Year with century as a decimal number 1970, 1988, 2001, 2013

Deze oefening maakt deel uit van de cursus

Financial Forecasting in Python

Cursus bekijken

Oefeninstructies

  • Import the datetime library.
  • Create a dt_object that converts the dates of each sale into a standardized format of day-month-year.
  • Print each result to compare

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Import the datetime python library
from ____ import ____

# Create a dt_object to convert the first date and print the month result
dt_object1 = datetime.strptime('14/02/2018', '____')
print(____)

# Create a dt_object to convert the second date and print the month result
dt_object2 = datetime.strptime('2 March 2018', '____')
print(____)
Code bewerken en uitvoeren