Home > other >  Generating a date in a particular format using python
Generating a date in a particular format using python

Time:09-19

I have a python code that looks like this. I am receiving the values of year, month and day in form of a string. I will test whether they are not null.

If they are not null I will like to generate a date in this format MMddyyyy from the variables

        from datetime import datetime

        year = "2022"
        month = "7"
        day = "15"

        if len(year) and len(month) and len(day):
            print('variables are not empty')
            #prepare = "{month}/{day}/{year}"
            #valueDt = datetime.strptime(prepare,"%m/%d/%Y")
        else:
            print('variables are empty')
            

The solution I have is not working. How can I generate this date?

CodePudding user response:

It should work without calling len as well.

from datetime import datetime, date

year = "2022"
month = "7"
day = "15"

if year and month and day:
    print('variables are not empty')
    prepare = date(int(year), int(month), int(day))
    valueDt = datetime.strftime(prepare, "%m/%d/%Y")
    print(valueDt)
else:
    print('variables are empty')

CodePudding user response:

from datetime import datetime, date

year = "2022"
month = "7"
day = "15"

if len(year) and len(month) and len(day):
    print('variables are not empty')
    prepare = date(int(year), int(month), int(day))
    valueDt = datetime.strftime(prepare, "%m/%d/%Y")
    print(valueDt)
else:
    print('variables are empty')
  • Related