2

I have a small problem with my date code. I would like the date to appear in Spanish add the date in Spanish.

The date is currently formatted like this: 2004/03/30

But I want the formatting to be like this: 04/21/2023

What I'm trying to do is display any date in Spanish, as follows: Viernes, 02 De Junio De 2023

Is there any way to do this?

The code I am using is the following:

from datetime import datetime, timedelta
s = '2004/03/30'
date = datetime.strptime(s, "%B")
modified_date = date + timedelta(days=1)
print(datetime.strftime(modified_date, "%B"))
QHarr
  • 83,427
  • 12
  • 54
  • 101
samantha
  • 23
  • 5
  • 4
    "2004/03/30", "04/21/2023" and "02 De Junio De 2023" are three entirely different dates. I suppose people will figure it out, but you get the best answers by using the most precise questions. – Tim Roberts Apr 21 '23 at 04:57

3 Answers3

2

I do not really understand how you want to convert the 30.March 2004, to 21.April 2023. But if you are only interested in the date format here is the code:

from datetime import datetime, timedelta
import locale

locale.setlocale(locale.LC_TIME, "es_ES")

s = '2004/03/30'
s_datetime = datetime.strptime(s, "%Y/%m/%d")
print(s_datetime) # 2004/03/30

date = datetime.strftime(s_datetime, "%m/%d/%Y")
print(date) # 03/30/2004

date_full = datetime.strftime(s_datetime, "%A, %d de %B de %Y")
print(date_full) # martes, 30 de marzo de 2004
print(date_full.title()) # Martes, 30 De Marzo De 2004

Here a strftime cheatsheet

GCMeccariello
  • 339
  • 2
  • 13
  • I like your solution. Do you have the spanish language package installed on your Operating System? When I execute your code on Github Codespaces I see only the english version of it - "Tuesday, 30 De March De 2004". – Luis Arteaga Apr 21 '23 at 09:28
  • 1
    In my case it is installed already. Otherwise check this out https://stackoverflow.com/a/2090861/16175571 – GCMeccariello Apr 21 '23 at 11:28
2

You can use the babel library to localize the date to Spanish.

pip install babel

The code would look like this:

from datetime import datetime
from babel.dates import format_date

s = '2004/03/30'
date = datetime.strptime(s, "%Y/%m/%d")

# Spanish locale
spanish_date = format_date(date, "EEEE, dd 'de' MMMM 'de' yyyy", locale='es')

print(spanish_date)

Output: martes, 30 de marzo de 2004

Luis Arteaga
  • 773
  • 8
  • 11
0

couldn't understand question, if you want exact convert date to spanish, this would help!

from datetime import datetime

input_date = '2004/03/30'
c_datetime = datetime.strptime(input_date, "%Y/%m/%d")
spanish_pattern = "%A, %d de %B de %Y"
spanish_format = c_datetime.strftime(spanish_pattern)
print(spanish_format)
kaavannan
  • 1
  • 1