2

I'm trying to run to following three lines of python code on command line using Python 3.5.0. It gives me an error- Attribute error: module 'datetime' has no attribute 'date'. I just want to print current date. Please help.

import datetime
current = datetime.date.today()
print(current)

3 Answers 3

2

There is nothing wrong with your code. It could be reduced a bit though:

import datetime
datetime.date

which should also cause the error. If this really causes the error, I would say your installation is messed up or, unlikely, there's a bug in Python. Please also make sure you don't have a datetime.py in your working directory. Further, check the output of dir(datetime) after importing it and with a different version of Python.

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

4 Comments

Thanks, my code worked. As @Ulrich said, the syntax was correct.The problem turned out to be with the file name. I had named the file as datetime.py. I re-named it to datetrial.py now.
Being able to resolve the name datetime.date is a prerequisite to using it, @Alasdair. The error clearly says that resolving the name already fails, hence the example code (remember, it's supposed to be a minimal example) could justifiably be reduced further. In other words, it doesn't do the same thing as in the question, but it fails for exactly the same reason, which is why it's equivalent.
@UlrichEckhardt apologies, I misunderstood your answer.
No offence taken, @Alasdair.
0

You shouldn't be getting any error running the above code as there is nothing wrong with it. Also rather than using the above code (which is okay syntax-wise but imports all the names accessible in the datetime moudule), you could use

from datetime import date
current = date.today()
print(current)

since all you want to import is the day's date.

Comments

0

the code returns date

when i run it on python 27. the code returns date with no errors!

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.