Print abbreviated month in python

2

I have a problem, how can I print the name of the month abbreviated in python using datetime

fecha= datetime.now()
print(f"Fecha:{fecha.hour}:{fecha.minute}   {fecha.day}/{fecha.month}/{fecha.year}");
input()
    
asked by Daniela Hernández 03.12.2018 в 08:12
source

2 answers

3

You do not need to extract the fields to print them as you do in the example of the question. The datetime dates have the .strftime() method which is passed a format string with a special syntax to specify which parts of the date and in which order you want them.

The format string for extracting the abbreviated month name is "%b" , so the following line would show the date in the format you wanted:

from datetime import datetime
fecha= datetime.now()
print(fecha.strftime("%H:%M %d/%b/%Y"))
08:37 03/Dec/2018

As you can see, the name of the month appears in English by default. If you want it to come out in another language you can change the locale . For example, to come out in Spanish:

import locale
locale.setlocale(locale.LC_ALL, ("es_ES", "UTF-8"))
print(fecha.strftime("%H:%M %d/%b/%Y"))
08:40 03/dic/2018
    
answered by 03.12.2018 в 09:42
0

What you can do, is to save yourself a dictionary that the key is the month of the year and the value the month.

#Mes completo, luego lo recortamos. Es por si lo necesitas despues
mesesDic = {
    "01":'Enero',
    "02":'Febrero',
    "03":'Marzo',
    "04":'Abril',
    "05":'Mayo',
    "06":'Junio',
    "07":'Julio',
    "08":'Agosto',
    "09":'Septiembre',
    "10":'Octubre',
    "11":'Noviembre',
    "12":'Diciembre'
}

Then you simply have to spend the year and you will get the month.

#Obtenemos el numero del mes actual.
mes = datetime.datetime.now().month
#Nos quedamos con los primero 3 caracteres
print(mesesDic[str(mes)][:3])
    
answered by 03.12.2018 в 08:55