How to convert user input date format to a different format on output in Python

Question:

I have a code where the date is an input converted to a date:

InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")

InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")

I would like to later output this date in the format of "DD-Mon-YY"

For example: 2022-03-30 to 30-Mar-22

Asked By: jonahpocalypse

||

Answers:

Maybe this is the code you are looking for:

year = input("Enter the year: ")
month = input("Enter the month: ")
day = input("Enter te day: ")
    
print(type(year))

if month == str(1):
    print(f"{day}-Jan-{year[2:]}")
elif month == str(2):
    print(f"{day}-Feb-{year[2:]}")
elif month == str(3):
    print(f"{day}-Mar-{year[2:]}")

and continuing the same way until we reach month == str(12) which is Dec

Answered By: m2r105

This will do what you require

InvDateStr = input("Enter the invoice date (YYYY-MM-DD): ")

InvDate = datetime.datetime.strptime(InvDateStr, "%Y-%m-%d")

InvDate = InvDate.strftime("%d-%b-%Y")
print(InvDate)

it uses strftime – more information on it can be found here https://pynative.com/python-datetime-format-strftime/#h-represent-dates-in-numerical-format

the %b simply translates a datetime month item into a 3 letter abbreviation. NOTE .strftime only works on datetime objects and not on str types

Hope this helps!

Answered By: Max Davies
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.