MartinT_25
MartinT_25

Reputation: 79

Datetime 'has no attribute now'

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') 

Upvotes: 6

Views: 35826

Answers (3)

Switnex XTra
Switnex XTra

Reputation: 11

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)

Upvotes: 1

Ibrahim Tayseer
Ibrahim Tayseer

Reputation: 566

import datetime
datetime.datetime.now()

Upvotes: 15

Yonas Kassa
Yonas Kassa

Reputation: 3720

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.

Upvotes: 4

Related Questions