6

I'm trying to write a simple program to print the current date with Python 3.4. In the shell, I can import datetime, and use now() but when I write a script with a class it fails and gives this error:

"AttributeError: module object has no attribute now". 

Can anyone help explain the problem? This is my code:

import datetime

class Date:
    def __init__(self, filename):
        self.writeToFile(filename)

    def date(self):
        now = datetime.datetime.now()
        return now

    def writeToFile(self, filename):
        date = self.date()

        file = open(filename, 'w')
        file.write(date)
        for i in range(20):             # simply test for writting in file
            file.write(str(i)+'\t')
        file.close()
        return file

d = Date('datetime.txt') 
SuperBiasedMan
  • 9,814
  • 10
  • 45
  • 73
MartinT_25
  • 79
  • 1
  • 1
  • 5
  • 10
    Your file isn't called `datetime.py`, is it? – SuperBiasedMan Jul 07 '15 at 11:58
  • 2
    What a stupid mistake :( I am really sorry for wasting your time, everybody's time a didnt realise that, this could be a problem..Thanks one more :) – MartinT_25 Jul 07 '15 at 12:04
  • Don't worry, we've all fallen into this trap before :) Remember that you should also be mindful of not using variable names like `list` that shadow the built-in names. These mistakes can lead to very puzzling errors... – Tim Pietzcker Jul 07 '15 at 12:53
  • I think everyone gets caught by this once and then passes on the knowledge. – SuperBiasedMan Jul 07 '15 at 13:46
  • @MartinT_25: [you are not alone](http://stackoverflow.com/q/25299371/4279) – jfs Jul 07 '15 at 20:29

3 Answers3

14
import datetime
datetime.datetime.now()
Ibrahim Tayseer
  • 518
  • 4
  • 10
4

Make sure you are importing the intended datetime module, and it is not being overridden by local files with same name. you can check it with:

import datetime
print(datetime.__file__)

and check the output if it is pointing to the correct directory you want.

Yonas Kassa
  • 3,362
  • 1
  • 18
  • 27
1

I had this error too and all I did was

Import datetime
from datetime import datetime

# then u can declare ur variable let's say something like
today = datetime.datetime.now()
#u can add what ever u want 
#the point is make sure u do the datetime.datetime.now()
print(today)
Stefano Sansone
  • 2,377
  • 7
  • 20
  • 39