transform dates in words to numeric dates

2

I have to turn dates into words into dates into numbers

21-MARZO-2017 
09-FEBRERO-2017
16-MAYO-2017

Which should look like this

21-03-2017
09-02-2017
16-05-2017

I tried to make an fix with the months and then compare them and replace them with the month by index of the array

 x = "21-MARZO-2017" 
 meses = ['enero','febrero','marzo','abril','mayo','junio','julio','agosto','septiembre','noviembre','diciembre']
 for i in meses 
    if meses not in x
       x = x.replace("MARZO", "index[meses]")
       print x 
    
asked by Pablo Vergara Rain 15.02.2017 в 16:01
source

2 answers

2

You can do this:

Code

def mesANumero(string):
    m = {
        'enero': "01",
        'febrero': "02",
        'marzo': "03",
        'abril': "04",
        'mayo': "05",
        'junio': "06",
        'julio': "07",
        'agosto': "08",
        'septiembre': "09",
        'octubre': "10",
        'noviembre': "11",
        'diciembre': "12"
        }

    fecha = string.split("-")
    dia =  fecha[0]
    mes =  fecha[1]
    anio = fecha[2]

    try:
        out = str(m[mes.lower()])
        print dia + "-" +  out + "-" + anio
    except:
        raise ValueError('No es un mes')

Example

>>> mesANumero("09-FEBRERO-2017")
09-02-2017

Explanation:

The variable m represents a dictionary where each month string is associated with a numeric value.

I do a split("-") to separate the string in 3: day, month and year.

within the try the pair that corresponds to the month that you passed the parameter is searched for and saves it in out. If you can not find it, give an error.

At the end it makes a print (you can change it for a return) together the day + the month number + the year

Note: If you have any questions about the code, let me know.

    
answered by 15.02.2017 / 16:28
source
1

I'm not an expert on python but I think using a function would be a little easier and 'nice' to solve your problem:

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

# Guardamos todos los meses dentro de un arreglo
months = ["ENERO", "FEBRERO", "MARZO", "ABRIL", "MAYO", "JUNIO", "JULIO", "AGOSTO", "SEPTIEMBRE", "OCTUBRE", "NOVIEMBRE", "DICIEMBRE"]

# Guardamos todas las fechas a convertir dentro de un arreglo
dates = ["21-MARZO-2017", "09-FEBRERO-2017", "16-MAYO-2017", "12-OCTUBRE-2016"]
# Creamos un arreglo vacío para guardar las fechas ya transformadas
newDates = []

# Creamos una función que nos devuelva el número de mes
# buscandolo por el nombre del mes
def getNumMonthByName(monthName):
    # Primero nos cercioramos de que el mes si esté en nuestro arreglo
    if(monthName in months):
        # Si el número de digitos de nuestro mes es '1'
        # le añadimos un 0 al principio (01 para enero, 02 para febrero, etc)
        if(len(str(months.index(monthName) + 1)) == 1):
            currentMonth = months.index(monthName) + 1
            return '0' + str(currentMonth)
        else:
            # Si no, lo retornamos tal cual
            return months.index(monthName) + 1
    else:
        return False

# Recorremos las fechas a convertir
for x in range(0, len(dates)):
    # Convertimos el string de la fecha a un arreglo donde
    # la posición 1 será el nombre del mes
    currentDateSplit = dates[x].split('-')

    # Transformamos nuestro mes
    newMonth = str(getNumMonthByName(currentDateSplit[1]))

    # Concatenamos y agregamos al arreglo las nuevas fechas transformadas
    newDates.append(str(currentDateSplit[0]) + "-" + newMonth + "-" + str(currentDateSplit[2]))

print(newDates)

With which we would have a console output like the following:

  

['21-03-2017', '09 -02-2017 ', '16 -05-2017', '12 -10-2016 ']

    
answered by 15.02.2017 в 16:34