Image like below
2019-01-07 00:00:00
⇒Tuesday
This article seemed to be helpful, so I almost copied and executed it. Get the day and month from the date in Python as a string (Japanese, English, etc.)
It seems that you can get it by changing the locale with the locale module.
import datetime import locale dt = datetime.datetime(2018, 1, 1) print(dt) # 2018-01-01 00:00:00 print(dt.strftime('%A, %a, %B, %b')) # Monday, Mon, January, Jan locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8') print(locale.getlocale(locale.LC_TIME)) # ('ja_JP', 'UTF-8') print(dt.strftime('%A, %a, %B, %b')) #Monday,Month,January, 1
There was a reference code like the one above, so when I ran it, I got an error ...
2018-01-01 00:00:00
Monday, Mon, January, Jan
Traceback (most recent call last):
File ".\time_test.py", line 11, in <module>
locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8')
File "C:\Users\XXXXX\AppData\Local\Programs\Python\Python37\lib\locale.py", line 604, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting
Since it says locale.Error: unsupported locale setting
, I feel that the language and region specified by setlocale
are incorrect.
Check the arguments passed by setlocale
properly.
locale --- Python documentation
First of all, it says to write the following code.
import locale locale.setlocale(locale.LC_ALL, '')
If you change the part of locale.setlocale (locale.LC_TIME,'ja_JP.UTF-8')
to the above writing style ...
time_test.py
import datetime
import locale
dt = datetime.datetime(2018, 1, 1)
print(dt)
# 2018-01-01 00:00:00
print(dt.strftime('%A, %a, %B, %b'))
# Monday, Mon, January, Jan
#locale.setlocale(locale.LC_TIME, 'ja-JP')
locale.setlocale(locale.LC_ALL, '')
print(locale.getlocale(locale.LC_TIME))
print(dt.strftime('%A, %a, %B, %b'))
#Monday,Month,January, 1
Output result
2018-01-01 00:00:00
Monday, Mon, January, Jan
('Japanese_Japan', '932')
Monday,Month,January, 1
I was able to display the day of the week I wanted to get.
Since the output result is ('Japanese_Japan', '932')
in print (locale.getlocale (locale.LC_TIME))
, it is presumed that the cause was specified by ja_JP
.
locale.setlocale (locale.LC_ALL,'')
Even if I changed it to locale.setlocale (locale.LC_TIME,'Japanese_Japan.UTF-8')
, it seemed that I could get Japanese results, so I executed it.
('Japanese_Japan', 'utf8')
Monday,Month,January, 1
I was able to get the expected results.
Recommended Posts