Ani*_*iya 3 python date-format
我想验证任何给定格式的日期格式。例如在法语中:14-déc-2017。在正常的英语语言14-Dec-2017是在%d-%b-%Y格式。我想要的是任何语言格式的日期都应该得到验证。
在python中,datetime我使用下面的函数来验证英文日期格式。
datetime.strptime('14-Dec-2017', '%d-%b-%Y')
Run Code Online (Sandbox Code Playgroud)
要验证任何其他语言的日期格式,使用哪个库/函数?
我认为你需要locale模块:
import time
import locale
locales = ['fr', 'zh', 'tr'] # french, chinese, turkish
for loc in locales:
locale.setlocale(locale.LC_ALL, loc)
print(time.strftime("%d-%b-%Y"))
12-déc.-2017
12-12?-2017
12-Ara-2017
>>>
Run Code Online (Sandbox Code Playgroud)
我在 Windows 10 上试过了。
编辑:如果您使用的是 Ubuntu,请sudo locale-gen 'fr' 'zh' 'tr'在命令行上运行。
之后,请尝试以下代码:
import time
import locale
locales = ['fr_FR.utf-8', 'zh_CN.utf-8', 'tr_TR.utf-8'] # french, chinese, turkish
for loc in locales:
locale.setlocale(locale.LC_ALL, loc)
print(time.strftime("%d-%b-%Y"))
12-déc.-2017
12-12?-2017
12-Ara-2017
>>>
Run Code Online (Sandbox Code Playgroud)
在@tripleee 的建议下,我在 Windows 子系统 Linux 上尝试了上述命令和 Python 代码,它按预期运行。
编辑 2:也许您需要一个函数,它接受语言环境和格式并以指定的格式返回日期:
import time
import locale
def get_date_in(loc, df):
formats = ["%d-%b-%Y", "%d %b %Y"] # Update formats here
for f in formats:
if f == df:
locale.setlocale(locale.LC_ALL, loc)
loc_date = time.strftime(f)
return loc_date
Run Code Online (Sandbox Code Playgroud)
Windows 10 上的演示:
french = get_date_in('fr', "%d-%b-%Y")
chinese = get_date_in('zh', "%d %b %Y")
turkish = get_date_in('tr', "%d-%b-%Y")
print(french)
print(chinese)
print(turkish)
12-déc.-2017
12 12? 2017
12-Ara-2017
>>>
Run Code Online (Sandbox Code Playgroud)
Ubuntu 16.04 上的演示:
french = get_date_in('fr_FR.utf-8', "%d-%b-%Y")
chinese = get_date_in('zh_CN.utf-8', "%d %b %Y")
turkish = get_date_in('tr_TR.utf-8', "%d-%b-%Y")
print(french)
print(chinese)
print(turkish)
12-déc.-2017
12 12? 2017
12-Ara-2017
>>>
Run Code Online (Sandbox Code Playgroud)
希望有帮助