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')
import datetime
datetime.datetime.now()
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.
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)
Related
What I am trying to do is, save each recorded file with a different filename(Myaudio1,2,3). Currently this code saves the audio as MYAUDIO.3gp, replacing the old file.
class MyRecorder:
def __init__(self):
'''Recorder object To access Android Hardware'''
self.MediaRecorder = autoclass('android.media.MediaRecorder')
self.AudioSource = autoclass('android.media.MediaRecorder$AudioSource')
self.OutputFormat = autoclass('android.media.MediaRecorder$OutputFormat')
self.AudioEncoder = autoclass('android.media.MediaRecorder$AudioEncoder')
# create out recorder
self.mRecorder = self.MediaRecorder()
self.mRecorder.setAudioSource(self.AudioSource.MIC)
self.mRecorder.setOutputFormat(self.OutputFormat.THREE_GPP)
self.mRecorder.setOutputFile('/sdcard/MYAUDIO.3gp')
self.mRecorder.setAudioEncoder(self.AudioEncoder.AMR_NB)
self.mRecorder.prepare()
I don't remember where I found the full code but if you need it, let me know. Thank you
You can use datetime for this.
from datetime import datetime
d = datetime.now()
d = d.strftime("%d_%m_%Y_%H%M%S")
self.mRecorder.setOutputFile('/sdcard/MYAUDIO_{}.3gp'.format(d))
Here is my Transaction class:
class Transaction(object):
def __init__(self, company, num, price, date, is_buy):
self.company = company
self.num = num
self.price = price
self.date = datetime.strptime(date, "%Y-%m-%d")
self.is_buy = is_buy
And when I'm trying to run the date function:
tr = Transaction('AAPL', 600, '2013-10-25')
print tr.date
I'm getting the following error:
self.date = datetime.strptime(self.d, "%Y-%m-%d")
AttributeError: 'module' object has no attribute 'strptime'
How can I fix that?
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime module also named their class datetime:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
Use the correct call: strptime is a classmethod of the datetime.datetime class, it's not a function in the datetime module.
self.date = datetime.datetime.strptime(self.d, "%Y-%m-%d")
As mentioned by Jon Clements in the comments, some people do from datetime import datetime, which would bind the datetime name to the datetime class, and make your initial code work.
To identify which case you're facing (in the future), look at your import statements
import datetime: that's the module (that's what you have right now).
from datetime import datetime: that's the class.
I got the same problem and it is not the solution that you told. So I changed the "from datetime import datetime" to "import datetime". After that with
the help of "datetime.datetime" I can get the whole modules correctly. I guess this is the correct answer to that question.
Values may differ depending on usage.
import datetime
date = datetime.datetime.now()
date.strftime('%Y-%m-%d') # date variable type is datetime
The value of the date variable must be a string::
date = '2021-09-06'
datetime.datetime.strptime(date, "%Y-%m-%d")
str(datetime.datetime.strptime(date, "%Y-%m-%d")) # show differently
The solutions mentioned by the others are correct. But for me, it was a problem with another library importing datetime module for me and overriding the datetime class I was importing.
an example with tsai library:
from datetime import datetime
from tsai.all import *
This will give you the error: 'module' object has no attribute 'strptime'.
In this case, just flip the order of imports or just don't import everything (even if the documentation does that) :
from tsai.all import *
from datetime import datetime
When I create my logfile, I want the name to contain the datetime.
In Python you can get the current datetime as:
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2012, 2, 3, 21, 35, 9, 559000)
The str version is
>>> str(datetime.now())
'2012-02-03 21:35:22.247000'
Not a very nice str to append to the logfile name! I would like my logfile to be something like:
mylogfile_21_35_03_02_2012.log
Is there something Python can do to make this easy? I am creating the log file as:
fh = logging.FileHandler("mylogfile" + datetimecomp + ".log")
You need datetime.strftime(), this allows you to format the timestamp using all of the directives of C's strftime(). In your specific case:
>>> datetime.now().strftime('mylogfile_%H_%M_%d_%m_%Y.log')
'mylogfile_08_48_04_02_2012.log'
You could also use a TimedRotatingFileHandler that will handle the date and the rollover every day (or whenever you want) for you.
from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile', when='midnight')
By default the format will be depending on the rollover interval:
The system will save old log files by appending extensions to the filename. The extensions are date-and-time based, using the strftime format %Y-%m-%d_%H-%M-%S or a leading portion thereof, depending on the rollover interval.
But you can modify that as showed here, by doing something like:
from logging.handlers import TimedRotatingFileHandler
fh = TimedRotatingFileHandler('mylogfile', when='midnight')
fh.suffix = '%Y_%m_%d.log'
Yes. Have a look at the datetime API, in particular strftime.
from datetime import datetime
print datetime.now().strftime("%d_%m_%Y")
Another Solution using format():
#generates a date for a generic filename
import datetime
date_raw = datetime.datetime.now()
date_processed = "{}-{}-{}_{}-{}-{}".format(date_raw.year, date_raw.month,
date_raw.day, date_raw.hour, date_raw.minute, date_raw.second)
#example value: date_processed = 2020-1-7_17-17-48
I used this in my own project
edit: as I found out about f(ormatted)-strings, this would be another solution:
date_processed = f"{date_raw.year}-{date_raw.month}-{date_raw.day}_{date_raw.hour}-{date_raw.minute}-{date_raw.second}"
We can use datetime.now() to get current timestamp. Here is my code that I am using to create log file with timestamp -
import logging
from datetime import datetime
LOG_FILENAME = datetime.now().strftime('D:/log/logfile_%H_%M_%S_%d_%m_%Y.log')
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
logging.info('Forecastiong Job Started...')
logging.debug('abc method started...')
from time import strftime
fh = logging.FileHandler(strftime("mylogfile_%H_%M_%m_%d_%Y.log"))
To print hour, minutes, day, month and year, use the following statement
from datetime import datetime
print datetime.now().strftime("%H_%M_%d_%m_%Y")
I have a script for deleting images older than a date.
Can I pass this date as an argument when I call to run the script?
Example: This script delete_images.py deletes images older than a date (YYYY-MM-DD)
python delete_images.py 2010-12-31
Script (works with a fixed date (xDate variable))
import os, glob, time
root = '/home/master/files/' # one specific folder
#root = 'D:\\Vacation\\*' # or all the subfolders too
# expiration date in the format YYYY-MM-DD
### I have to pass the date from the script ###
xDate = '2010-12-31'
print '-'*50
for folder in glob.glob(root):
print folder
# here .jpg image files, but could be .txt files or whatever
for image in glob.glob(folder + '/*.jpg'):
# retrieves the stats for the current jpeg image file
# the tuple element at index 8 is the last-modified-date
stats = os.stat(image)
# put the two dates into matching format
lastmodDate = time.localtime(stats[8])
expDate = time.strptime(xDate, '%Y-%m-%d')
print image, time.strftime("%m/%d/%y", lastmodDate)
# check if image-last-modified-date is outdated
if expDate > lastmodDate:
try:
print 'Removing', image, time.strftime("(older than %m/%d/%y)", expDate)
os.remove(image) # commented out for testing
except OSError:
print 'Could not remove', image
The quick but crude way is to use sys.argv.
import sys
xDate = sys.argv[1]
A more robust, extendable way is to use the argparse module:
import argparse
parser=argparse.ArgumentParser()
parser.add_argument('xDate')
args=parser.parse_args()
Then to access the user-supplied value you'd use args.xDate instead of xDate.
Using the argparse module you automatically get a help message for free when a user types
delete_images.py -h
It also gives a helpful error message if the user fails to supply the proper inputs.
You can also easily set up a default value for xDate, convert xDate into a datetime.date object, and, as they say on TV, "much, much more!".
I see later in you script you use
expDate = time.strptime(xDate, '%Y-%m-%d')
to convert the xDate string into a time tuple. You could do this with argparse so args.xDate is automatically a time tuple. For example,
import argparse
import time
def mkdate(datestr):
return time.strptime(datestr, '%Y-%m-%d')
parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)
when run like this:
% test.py 2000-1-1
yields
time.struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=1, tm_isdst=-1)
PS. Whatever method you choose to use (sys.argv or argparse), it would be a good idea to pull
expDate = time.strptime(xDate, '%Y-%m-%d')
outside of the for-loop. Since the value of xDate never changes, you only need to compute expDate once.
Little bit more polish to unutbu's answer:
import argparse
import time
def mkdate(datestr):
try:
return time.strptime(datestr, '%Y-%m-%d')
except ValueError:
raise argparse.ArgumentTypeError(datestr + ' is not a proper date string')
parser=argparse.ArgumentParser()
parser.add_argument('xDate',type=mkdate)
args=parser.parse_args()
print(args.xDate)
The command line options can be accessed via the list sys.argv. So you can simply use
xDate = sys.argv[1]
(sys.argv[0] is the name of the current script.)
you can use runtime arguments for this approach. Please see following link: http://www.faqs.org/docs/diveintopython/kgp_commandline.html
How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?
Use ntplib. Right from the manual:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
Just to save you some time. Here's the code I ended up with using phihag's answer. It prints the drift every interval_sec to screen and to a log file.
You'll need to easy_install ntplib for it to work.
import logging
logging.basicConfig(filename='time_shift.txt',level=logging.DEBUG)
import ntplib
import time
import datetime
c = ntplib.NTPClient()
interval_sec = 60
while True:
try:
response = c.request('europe.pool.ntp.org', version=3)
txt = '%s %.3f' % (datetime.datetime.now().isoformat(), response.offset)
print txt
logging.info(txt)
except:
pass
time.sleep(interval_sec)