ComenzarEmpieza gratis

Convertir formatos de fecha: sencillo

El área de ventas A en Europa y el área de ventas B en Australia tienen formatos de fecha diferentes.

  • Venta A: 4000 el 14/02/2018
  • Venta B: 3000 el 2 March 2018

Si queremos consolidar o comparar periodos de ventas, necesitamos convertir al mismo formato de fecha. Podemos hacerlo fácilmente usando la biblioteca datetime y el método datetime.strptime(date_string, format), utilizando las siguientes directivas:

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

Este ejercicio forma parte del curso

Financial Forecasting in Python

Ver curso

Instrucciones del ejercicio

  • Importa la biblioteca datetime.
  • Crea un dt_object que convierta las fechas de cada venta a un formato estándar día-mes-año.
  • Imprime cada resultado para comparar

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

# 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(____)
Editar y ejecutar código