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

Time:10-19

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

CodePudding user response:

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!

CodePudding user response:

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

  • Related