James_1751
James_1751

Reputation: 1

Outputting datetime in a loop is failing

My aim is to run ipconfig every 10 seconds for 1000 times, writing the output of the command to a text file containing the date. The problem with my code below is that once it begins the 2nd run through of the loop, it coughs up:

datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
AttributeError: 'str' object has no attribute 'datetime'

import datetime
import os
import time

count=0
while (count < 1000):
    print '--------------------------------------------------------'
    print count
    datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
    print datetime
    os.system("ipconfig > ipconfig_" + datetime)
    print '--------------------------------------------------------'
    time.sleep(10)
    count = count + 1
print "Good bye!"

Any ideas where I'm going wrong? Many thanks.

Upvotes: 0

Views: 36

Answers (1)

Rahul R
Rahul R

Reputation: 31

Looks like you are re-using the datetime variable in the code. In the first run, it works fine because datetime is the imported module. Then, on

datetime = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
# datetime is now a string storing the date time in the format specified

In the second run, the code now crashes in the rhs of the same line as there is no property datetime in the string datetime

Fixed code:

import datetime
import os
import time

count=0
while (count < 1000):
    print '--------------------------------------------------------'
    print count
    date_time = datetime.datetime.now().strftime("%Y-%m-%d_%H%M")
    print date_time
    os.system("ifconfig > ifconfig_" + date_time)
    print '--------------------------------------------------------'
    time.sleep(10)
    count = count + 1
print "Good bye!"

Upvotes: 2

Related Questions