[英]Python: convert date format YYYY-mm-dd to dd-MON-yyyy with abbreviated month
I have a date that is a string in this format:我有一个日期是这种格式的字符串:
'2021-01-16'
And need to convert it to a string in this format:并且需要将其转换为这种格式的字符串:
'16-JAN-2021'
I am able to get most of it like this:我能够像这样获得大部分内容:
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
x.strftime('%d-%b-%Y')
But the month is not fully capitalized:但是月份没有完全大写:
'16-Jan-2021'
Just use upper()
to capitalize the output string:只需使用
upper()
将 output 字符串大写:
from datetime import datetime
x = datetime.strptime('2021-01-16', '%Y-%m-%d')
print(x.strftime('%d-%b-%Y').upper())
# 16-JAN-2021
You were almost there.你快到了。 Simply use upper().
只需使用upper()。
>>> from datetime import datetime
>>> datetime.strptime('2021-01-16', '%Y-%m-%d').strftime('%d-%b-%Y').upper()
'16-JAN-2021'
x.strftime('%d-%b-%Y').upper()
I read answers with upper()
function, here is another way using %^b
我用
upper()
function 阅读答案,这是另一种使用%^b
的方法
from datetime import datetime
date = datetime.strptime('2011-01-16', '%Y-%m-%d')
formatted_date = date.strftime('%d-%^b-%Y')
print(formatted_date)
Goodluck!祝你好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.