如何创建新的日期时间格式以供使用?

huangapple go评论68阅读模式
英文:

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

英文:

localeis 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.

huangapple
  • 本文由 发表于 2023年2月14日 18:41:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75446671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定