Datetime and Time can't be used in the same program? - python

So I'm writing a program with
import datetime
import time
I'm using time to record the time it takes the program to run, and I need to check the date so if the file is more than a certain age, don't process it.
I keep getting this error when trying to use these two classes
Traceback (most recent call last):
File "<stdin>", line 563, in <module>
File "<stdin>", line 498, in main
AttributeError: type object 'datetime.time' has no attribute 'time'
shell returned 1
Is it not possible to use both time and datetime in one program?
Some of the code:
import PyPDF2
import re
import os
#Time testing
import time
#Using this to check if address is in proper format and to clean it up
import usaddress
#testing this one out
import datetime
from dateutil.parser import *
from dateutil.tz import *
from datetime import *
#Timer starts
start_time = time.time() #Error is referring to this line, line 498
#Opens 3 different files
#For file in folder parse it to text
#Writes some things to file
#Gets the date from the file
if date != None:
fileDate = parse(date).year
now = datetime.now()
print now.year, now.month, now.day
#Ends the timer and prints the time to the console
print("--- %s seconds ---" % round(time.time() - start_time, 2))

Here is your problem:
import datetime
from dateutil.parser import *
from dateutil.tz import *
from datetime import * # <<<< problems
First you are importing datetime and then you are importing everything from datetime.
Be explicit, and only import what you need.
from datetime import datetime
Then you can use it as datetime.now or whatever methods you may need.
As a rule of thumb, never import *. It causes exactly these sorts of issues.

The problems is:
from datetime import *
because it imports time from datetime. It's always better to import only what you need. But if you also really need this method you could do (for example):
from datetime import time as dt
That's why import * is dangerous...

Related

import datetime - Clarification

''''
from datetime import datetime
now = datetime.now().time()
print(now)
o/p: 21:44:22.612870
''''
But, when i am trying:
''''
import datetime
now = datetime.now().time()
print(now)
''''
it give following error:
Traceback (most recent call last):
File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in
now = datetime.now().time() # time object
AttributeError: module 'datetime' has no attribute 'now'
any one explain what is difference between both?
The datetime library exports a module called datetime.
Modules are Python .py files that consist of Python code. Any Python file can be referenced as a module.
if you want you can also use it this way:
import datetime
datetime.datetime.now()

Python module 'modules' has no attribute 'millis'

Completely new to Python, I have installed the latest stock version, updated PIP and tried to run a script been given to import data from API (person provided says works for them), when tried to run I have installed each library as required.
import json
import pandas as pd
from pandas.io.json import json_normalize
import requests
import modules
from requests_oauthlib import OAuth1
from datetime import datetime
this is main header, I am now getting error AttributeError: module 'modules' has no attribute 'millis' on following line
payload = {'interactive': 'true',
"ended": 'true',
"start": {"from": modules.millis(2019,4,21,0,0), # CHANGE HERE THE DATE
"to": modules.millis(2019,4,24,23,59)}, # CHANGE HERE THE DATA
'skillIds':['1286977632']
}
Any ideas.
sorry guys I have found the fix, it was in a separate file I was not given at the time
# returns the elapsed milliseconds since the start of the program
def millis(year,month,day,hour,minute):
dt = datetime(year,month,day,hour, minute) - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
return round(ms)

AttributeError: 'list' object has no attribute 'astimezone'

My python script:
import ftplib
import hashlib
import httplib
import pytz
from datetime import datetime
import urllib
from pytz import timezone
import os.path, time
import glob
def ftphttp():
files = glob.glob('Desktop/images/*.png')
ts = map(os.path.getmtime, files)
dts = map(datetime.fromtimestamp, ts)
print ts
timeZone= timezone('Asia/Singapore')
#converting the timestamp in ISOdatetime format
localtime = dts.astimezone(timeZone).isoformat()
I was trying to get the multiple files timestamp. I able to print out all the files in my folder
[1467910949.379998, 1466578005.0, 1466528946.0]
But it also prompt me this error about the timezone. Anybody got any ideas?
Traceback (most recent call last):
File "<pyshell#76>", line 1, in <module>
ftphttp()
File "/home/kevin403/Testtimeloop.py", line 22, in ftphttp
localtime = dts.astimezone(timeZone).isoformat()
AttributeError: 'list' object has no attribute 'astimezone'
You are trying to call a method on a list of objects, instead of the objects in the list. Try calling the method on the first object instead:
localtime = dts[0].astimezone(timeZone).isoformat()
Or map over the list to get all timestamps in iso format:
localtimes = map(lambda x: x.astimezone(timeZone).isoformat(), dts)
dts is a list of time zones. So you need to do:
[ts.astimezone(timeZone) for ts in dts]
This will give you a list of the three time zones

Getting error for datetime in python

I have a file named global.py and a function to create report :
import datetime
class customFail(Exception):pass
def createReport(myModule,iOSDevice,iOSVersion):
now=datetime.datetime.now()
resultPath="../Results"
resultFile="Result_%d_%d_%d_%d_%d_%d.html" % (now.day,now.month,now.year,now.hour,now.minute,now.second)
fileName="%s/%s" % (resultPath,resultFile)
fNameObj=open("../Results/resfileName.txt","w") #Writing result filename temporary
fNameObj.write(fileName) #in a file to access this filename by other functions (rePass,resFail)
fileObj=open(fileName,"w")
fileObj.write("<html>")
fileObj.write("<body bgcolor=\"Azure\">")
fileObj.write("<p> </p>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:LemonChiffon;\">")
fileObj.write("<td width=\"40%\"><b>Module : </b>"+ myModule+"</td>")
fileObj.write("<td width=\"30%\"><b>Time : </b>"+ now.strftime("%d-%m-%Y %H:%M")+"</td>")
fileObj.write("</tr>")
fileObj.write("<tr>")
fileObj.write("</tr>")
fileObj.write("</table>")
fileObj.write("<table width=\"600\" border=\"5\">");
fileObj.write("<tr style=\"background-color:BurlyWood;\">")
fileObj.write("<td width=\"70%\"><b>Device : </b>"+ iOSDevice+" - <b> Version : </b>"+ iOSVersion+"</td>")
fileObj.write("</tr>")
fileObj.write("</table>")
#fileObj.write("<br>")
and a script file where i call this function called scripts.py
import os
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import WebDriver
from selenium.webdriver.common.action_chains import ActionChains
import time
import sys
sys.path.append('/Users/admin/Desktop/_Suite/Global Scripts/')
from funcLib import *
from myGlobal import *
wd = deviceSelection();
iOSVersion="i7"
iOSDevice="iPhone"
modName="BAT"
suiteStartTime=0
def main():
start()
fntesttrial();
finish();
def start():
global modName,suiteStartTime
global appName,ctx_app,ctx_simulator
suiteStartTime=time.time();
createReport(modName,iOSDevice,iOSVersion)
stts=api_clr_acnt.fnClearAccount(myDict["UserName"],myDict["Password"],myDict["Environment"])
def fntesttrial():
try:
wd.find_element_by_name("Accept").click()
time.sleep(5)
wd.find_element_by_name("Sign In").click()
time.sleep(5)
wd.find_element_by_name("Need help?").click()
time.sleep(5)
wd.find_element_by_name("Close").click()
time.sleep(5)
finally:
wd.quit()
main()
When I run this i am getting error like :
now=datetime.datetime.now()
NameError: global name 'datetime' is not defined
I am not understanding why I am getting that error. Please help me since i am new to python.
I think you need to import datetime at the top of the script file (code block 2). It gives you the error because datetime is indeed undefined in the script, as it hasn't been imported yet.
When you call "createReport()", "now" can't be defined, as it calls on the datetime module, which isn't imported.
If you wanted, you could write import datetime at the start of the method definition, but if you called the method twice, it would import datetime twice, so you're probably better off just importing it at the start of the second codeblock.

problems with data in python

I have code in django:
for i in range(int(cac)):
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M") - datetime.timedelta(minutes=i)
and have some of this errors :
type object 'datetime.datetime' has no attribute 'datetime'
or
type object 'datetime.time' has no attribute 'mktime'
or somethings else.
I try few examples:
import datetime
import time
or
from datetime import datetime
or
from datetime import *
from time import *
explain me what I do wrong?
thanks
Check all your imports. If you import in models like
from datetime import datetime
and then import
from .models import *
so you will have errors like this. Check all your imports.
Try this:
import datetime
for i in range(int(cac)):
print (datetime.datetime.now() - datetime.timedelta(minutes=i)).strftime('%Y-%m-%d %H:%M')

Categories

Resources