Extracting Information


This is my syntax, which appears to be correct, but the code keeps running. Please advise.


Ian Michael Jones

from datetime import datetime
now = datetime.now()
print datetime.now()
now = now.year
print now.year
print now.month
print now.day


Hi @dio123
Running your code gives below error :

2015-12-02 17:33:47.079627
Traceback (most recent call last):
File "python", line 5, in
AttributeError: 'int' object has no attribute 'year'

Let me explain this.
In line no.2 you are assigning today's date to a variable now

now = datetime.now()

In line no 3 you are printing datetime.now() which is the 1st line of the output.

Now in line no 4

now = now.year

you are over-writing "now" variable with the year part of todays date. So if you're running that piece of code today, then "now" variable as of line no 4 will have 2015 assigned to it. It no longer has the date in it.
That explains the error in the stack trace which suggests there isn't a 'year' attribute associated with an integer.
Hope this clarifies your doubt.