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

Navi
  • 1,000
  • 1
  • 14
  • 44
  • 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. – tobias_k Jul 05 '18 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) – Thibault D. Jul 05 '18 at 13:13
  • Check [this question](https://stackoverflow.com/questions/11620151/what-do-numbers-starting-with-0-mean-in-python). Also [this PEP](https://www.python.org/dev/peps/pep-3127/) may be useful – Ketan Mukadam Jul 05 '18 at 13:17
  • Why do you need to write the month parameter of `datetime()` with a leading zero? Just wondering. – CZoellner Jul 05 '18 at 15:53

5 Answers5

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
miw
  • 776
  • 4
  • 11
1

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

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39
1

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

I tried in the console

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
1

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

"{:02d}".format(your_number)
JeffUK
  • 4,107
  • 2
  • 20
  • 34
Dourave
  • 43
  • 1
  • 6
0

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

Datetime knows what 9 is, no need to put 09