Reputation: 63
I'm trying to convert yyyy/mm/dd to dd/mm/yyyy, from integer inputs.
When i've changed the pattern inside the parethesis from datetime.date(year, month, day)
, to datetime.date(day, month, year)
, it returns an Value error.
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(day, month, year)
return exp_date
ValueError: day is out of range for month
Upvotes: 0
Views: 184
Reputation: 1049
From the documentation:
class datetime.date(year, month, day)
This means you need to put the arguments in the right position, doesn't matter how you want to print it later.
This should work:
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(year, month, day)
return exp_date
Now let's print it formatted in dd/mm/yyyy:
d = acc_expiration()
f = d.strftime('%d/%m/%Y')
print(f) # prints it formatted dd/mm/yyyy
Your value error is because you are giving a year integer (integer bigger than 31) to the day argument, and for the year you are giving the day integer.
Upvotes: 1
Reputation: 31
You are confusing the object from its presentation.
Look at the Python docs for Datetime (here)
The correct sequence for datetime.date is class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
Once you have a datetime object, you can format the output of it in a variety of ways to suit your needs.
Does that help?
Upvotes: 0