英文:
How to create new date format for datetime to use?
问题
I want to convert a list of dates into another format. Until now it was easy because the dates that I had to convert were in this format: %d-%b-%Y (example 13-Jan-2023). So I could just "tell" python that it was in this format and that it should convert it to : %d/%m/%Y (example 13/01/2023).
However, the initial date format has changed to 13-janv.-2023 (per example), so the months are now in French and abbreviated (janv. ; févr. ; mars ; avr. ; mai ; juin ; juil. ; sept. ; oct. ; nov. ; déc.
I can imagine that there must be a way to define a dictionary such as "Jan : janv." and then define it as a new format, but I have not succeeded yet. Your help will be appreciated.
Thanks
I am sorry, I have not found a similar question...
英文:
I am quite new to programming so please excuse if I don't use the correct terms.
I want to convert a list of dates into another format. Until now it was easy because the dates that I had to convert were in this format: %d-%b-%Y (example 13-Jan-2023). So I could just "tell" python that it was in this format and that it should convert it to : %d/%m/%Y (example 13/01/2023).
However, the initial date format has changed to 13-janv.-2023 (per example), so the months are now in french and abbreviated (janv. ; févr. ; mars ; avr. ; mai ; juin ; juil. ; sept. ; oct. ; nov. ; déc.
I can imagine that there must be a way to define a dictionary such as "Jan : janv. ", and then define it as a new format but I have not succeeded yet. Your help will be appreciated.
Thanks
I am sorry, I have not found a similar question...
答案1
得分: 0
locale
是处理特定地区主题的有用工具。
from datetime import datetime as dt
import locale
locale.setlocale(locale.LC_TIME, "fr_FR")
date_fr = '13-janv.-2023'
dt.strptime(date_fr, '%d-%b-%Y').strftime('%d/%m/%Y')
返回您所需的结果。但要注意!在设置了区域设置后,您不能再解析初始的 ('13-Jan-2023') 格式,除非您将区域设置改回。
解释:
strptime
用于_解析_您的输入,因此函数名称中有 p。
strftime
用于_格式化_日期/时间,因此函数名称中有 f。
英文:
locale
is your friend for region-specific topics.
from datetime import datetime as dt
import locale
locale.setlocale(locale.LC_TIME, "fr_FR")
date_fr = '13-janv.-2023'
dt.strptime(date_fr, '%d-%b-%Y').strftime('%d/%m/%Y')
Returns your desired result. But be aware! After setting your locale, you can't parse your initial ('13-Jan-2023') format anyore until your change the locale back.
Explanation:
strptime
is to parse your input, hence the p in the function name
strftime
is to format your date/time, hence the f.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论