1

I have been trying this code to get the september month as 09 in my code, but later i come to know that 09 is not acceptable in python. But it may displayed as a string only. My question is how to diplay the 09 as an integer?

My code:

    september_month = dt.datetime(int(self.year.name),09,30)   
    print september_month

Error: Invalid token 09 and ValueError: day is out of range for month

This python program runs in odoo version 10 python2.7

4
  • 3
    You can't. 09 as an integer is the same as 9 as an integer. If you want to display the leading 0, format it as a string. Also, in older version of Python, like 2.7, numbers starting with 0 are interpreted as octal, probably leading to much confusion. Commented Jul 5, 2018 at 13:10
  • 1
    Beware, in python, an integer beginning with a '0' is interpreted as an octal number, thus 09 is invalid and might raise a SyntaxError with invalid token (08 would do the same) Commented Jul 5, 2018 at 13:13
  • Check this question. Also this PEP may be useful Commented Jul 5, 2018 at 13:17
  • Why do you need to write the month parameter of datetime() with a leading zero? Just wondering. Commented Jul 5, 2018 at 15:53

6 Answers 6

3

In Python (in any version), a literal like 09 is interpreted as an octal literal. The value of 9 is therefore invalid.

If you really want to see the 09 you could write a string and convert to integer using int("09"). In your code:

september_month = dt.datetime(int(self.year.name),int("09"),int("30"))   
print september_month

Not sure whether this helps readability, really.

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to display the leading 0, format your number as a string:

"{:02d}".format(your_number)

1 Comment

This is an elegant option. You can also use it in an f-string f"{your_number:02d}"
1

It's not possible in Python 3 to write int values as 01,02,09 etc.

2 Comments

I asked for python 2.7
Same answer for python 2.7.
1

Man, it works, your problem is that there is no 31 of september

I tried in the console

Comments

0

https://docs.python.org/3.6/library/datetime.html

Datetime knows what 9 is, no need to put 09

Comments

0

Another way:

number = 9
formatted_number = str(number).zfill(4)
print(formatted_number)  # Output: '0009'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.