sanjayr
sanjayr

Reputation: 1949

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'

Upvotes: 4

Views: 13120

Answers (4)

Ahmed Abuamra
Ahmed Abuamra

Reputation: 213

I read answers with upper() function, here is another way using %^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!

Upvotes: 1

JumpinJim
JumpinJim

Reputation: 41

x.strftime('%d-%b-%Y').upper()

Upvotes: 2

ApplePie
ApplePie

Reputation: 8942

You were almost there. Simply use upper().

>>> from datetime import datetime
>>> datetime.strptime('2021-01-16', '%Y-%m-%d').strftime('%d-%b-%Y').upper()
'16-JAN-2021'

Upvotes: 1

Kien Nguyen
Kien Nguyen

Reputation: 2701

Just use upper() to capitalize the output string:

from datetime import datetime

x = datetime.strptime('2021-01-16', '%Y-%m-%d')

print(x.strftime('%d-%b-%Y').upper())
# 16-JAN-2021

Upvotes: 7

Related Questions