I have parsed a Russian date format as a string:
16 август 2021 which is 16 august 2021
I need to transfor it into a normal date stamp as: 2021-08-16
I've tried something like this:
date = 16 август 2021
from babel.dates import format_datetime
import datetime
format_datetime(date, locale='en_US')
but it does not work.
How can I do it?
CodePudding user response:
You need to setlocale()
to ru_RU
to parse dates with Russian names for months, weekdays, am/pm, etc.
setlocale()
is not thread-safe on most systems.
And then use the correct format codes with datetime.strptime()
:
from datetime import datetime
import locale
date = '16 август 2021'
locale.setlocale(locale.LC_ALL, 'ru_RU')
d = datetime.strptime(date, '%d %B %Y')
print(repr(d)) # datetime.datetime(2021, 8, 16, 0, 0)
print(d) # 2021-08-16 00:00:00
locale.setlocale(locale.LC_ALL, '') # setlocale to the system default once done
And as @deceze mentioned above, you should be parsing the date-string to create a datetime obj, not creating a new string from the string you already have. If you need that, do that as the next step.
# using `d` above
locale.setlocale(locale.LC_ALL, '') # en for me
print(datetime.strftime(d, '%d %B %Y')) # 16 August 2021
CodePudding user response:
Try that :
import locale
from datetime import date
from datetime import datetime
locale.setlocale(locale.LC_TIME, "en")
date.today().strftime("%d %B %Y")
CodePudding user response:
Refering to my previous answer: Unless it automatically knows its august (built in) and suppose you don't have to covert it to english equivalent, another problem would be passing its value. It expects to be datetime eg:
dt = datetime(2007, 4, 1)
format_datetime(dt, locale='en_US')
output: Apr 1, 2007