SyntaxError: invalid token in datetime.datetime(2012,05,22,09,03,41)?

Question:

I do something like this:

>>>import datetime
>>>datetime.datetime(2012,05,22,05,03,41)
datetime.datetime(2012, 5, 22, 5, 3, 41)

>>> datetime.datetime(2012,05,22,07,03,41)
datetime.datetime(2012,05,22,07,03,41)

>>> datetime.datetime(2012,05,22,9,03,41)
datetime.datetime(2012, 5, 22, 9, 3, 41)

>>> datetime.datetime(2012,05,22,09,03,41)
SyntaxError: invalid token

Why I get SyntaxError? How to fix it?

Asked By: user7172

||

Answers:

In Python 2, a number starting with 0 is interpreted as an octal number, often leading to confusion for those not familiar with C integer literal notations. In Python 3, you cannot start a number with 0 at all.

Remove the leading 0s:

datetime.datetime(2012, 5, 22, 9, 3, 41)

The error is caused by 09 not being a valid octal number:

>>> 010
8
>>> 09
  File "<stdin>", line 1
    09
     ^
SyntaxError: invalid token
Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.