Odoo Import Libaray - python

I am trying to write a server action for odoo8, the server action will give me the dates between two dates based on specific interval.
So i used the following code:
from datetime import datetime
from dateutil import relativedelta
startDate = object.x_start_datetime
endDate = object.x_stop_datetime
periodicity = object.x_periodicity.x_nb
visits = []
nxt = startDate
delta = relativedelta(**{'days':periodicity})
while nxt <= endDate:
result.append(nxt)
nxt += delta
raise Warning('Data: ' + startDate + " | " + result)
I was getting error regarding the import so i modified the file (openerp/tools/safe_eval.py) to add the IMPORT_NAME and IMPORT_FROM, also i added ('datetime', 'dateutil', 'relativedelta') to the allowed modules, but now it's giving the following error:
File "/opt/odoo/odoo-server/openerp/tools/safe_eval.py", line 228, in _import
return import(name, globals, locals, level)
ValueError: "'int' object does not support indexing" while evaluating
your help is appreciated.

Related

Problem with cycled import in datetime in python

Hi I have 2 functions these functions have a different types of import of datetime. I know where is problem but I do not know how to solute it
my code:
from datetime import datetime
import datetime
def upload_video(title,description,tags,upload_year,uplaod_month,upload_day):
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00, 0).isoformat() + '.000Z'
print(f"this is a upload time {upload_date_time}")
request_body = {
'snippet': {
'categoryI': 19,
'title': title,
'description': description,
'tags': tags
},
'status': {
'privacyStatus': 'private',
'publishAt': upload_date_time,
'selfDeclaredMadeForKids': False,
},
'notifySubscribers': False
}
mediaFile = MediaFileUpload('output.MP4')
response_upload = service.videos().insert(
part='snippet,status',
body=request_body,
media_body=mediaFile
).execute()
def date_calculator():
days_in_months = {1:31, 2:28, 3:31, 4:30, 5:31, 6:30, 7:31, 8:31, 9:30, 10:31, 11:30, 12:31}
year = datetime.now().year
month = datetime.now().month
# Read the last used date from the text file
with open("last_used_date.txt", "r") as f:
last_used_date = f.read().strip()
# If the file is empty or the date is invalid, set the last used date to the current date
if not last_used_date or not all(c.isdigit() for c in last_used_date.split(".")):
last_used_day = datetime.now().day
last_used_month = month
else:
last_used_day, last_used_month = map(int, last_used_date.split(".")[:2])
# Generate new dates until the next one is greater than the current date
number = 0
number_test = 1
while True:
date = "{}.{}.{}".format(last_used_day, last_used_month, year)
number += 1
if last_used_day == days_in_months[month]:
last_used_month += 1
last_used_day = 1
else:
last_used_day += 1
if number == 2:
last_used_day += 1
number = 0
number_test += 1
if (last_used_month > month or
(last_used_month == month and last_used_day > datetime.now().day)):
with open("last_used_date.txt", "w") as f:
f.write("{}.{}.{}".format(last_used_day, last_used_month, year))
break
return last_used_day,last_used_month,year
error:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 233, in
day,month,year = date_calculator() File "c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 162, in date_calculator
year = datetime.now().year AttributeError: module 'datetime' has no attribute 'now'
if I will change imports like this:
import datetime
from datetime import datetime
error will look like that:
Traceback (most recent call last): File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 235, in
upload_video(title,"#Shorts", ["motivation", "business", "luxury", "entrepreneurship", "success", "lifestyle", "inspiration", "wealth",
"financial freedom", "investing", "mindset", "personal development",
"self-improvement", "goals", "hustle", "ambition", "rich life",
"luxury lifestyle", "luxury brand", "luxury travel", "luxury
cars"],year,month,day) File
"c:\Users\Lukas\Dokumenty\python_scripts\Billionare
livestyle\main.py", line 74, in upload_video
upload_date_time = datetime.datetime(upload_year,uplaod_month,upload_day, 8, 00,
0).isoformat() + '.000Z' AttributeError: type object
'datetime.datetime' has no attribute 'datetime'
Unfortunately, the datetime module and the datetime class inside it are spelled exactly the same way. You need to pick one of those things to import and then use it consistently. i.e. either:
import datetime # I want the whole datetime module
datetime.datetime.now() # Must use the fully qualified class name
datetime.date.today() # But I can also use other classes from the module
Or:
from datetime import datetime # I only want the datetime class
datetime.now() # Use the class directly
The name datetime can only mean one thing at a time, so if you do both imports, all that's happening is that the second meaning overwrites the first one.

pywintypes.com_error. in Outlook. I am creating an outlook appointment, it errors on assigning time. Says that the object doesn't support method

I have this code:
import win32com.client
import pythoncom
import datetime
def saveMeeting(start, end, subject, location, attachments, recipients):
outlook = win32com.client.Dispatch("Outlook.Application", pythoncom.CoInitialize())
ns = outlook.GetNamespace("MAPI")
session = ns.Session
## Find the accounts that are of exchange type
acc = []
for account in session.Accounts:
if account.AccountType == 0: #0 - outlookExchange, 1 - outlookIMAP, 2 - outlookPop3
#print(account)
acc.append(account)
appointment = outlook.CreateItem(1) #1 - AppointmentItem
# Fill in the data needed
appointment.SendUsingAccount = acc
appointment.Start = datetime.datetime.strptime(start, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.StartTimeZone = outlook.TimeZones("Central Standard Time")
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
appointment.EndTimeZone = outlook.TimeZones("Central Standard Time")
appointment.Subject = f"HOLDER-{subject}"
appointment.Location = location
appointment.MeetingStatus = 1
if attachments != '':
appointment.Attachments.Add(attachments)
recipients = filter(None, recipients)
for recipient in recipients:
r = appointment.Recipients.Add(recipient)
r.Resolve()
appointment.Save()
# Only use .Display() if using tkinter
appointment.Display()
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["altisjessienino18#gmail.com", "ajn_dulay#smcm.edu.ph"])
But, it just gives me this error.
Traceback (most recent call last):
File "C:\Users\user\Desktop\Project\createInvite.py", line 100, in <module>
saveMeeting("2022-03-02 14:00:00", "2022-03-02 14:30:00", "Subject of the Meeting","Location", "", ["user1#gmail.com", "user2#smcm.edu.ph"])
File "C:\Users\user\Desktop\Project\createInvite.py", line 42, in saveMeeting
appointment.End = datetime.datetime.strptime(end, "%Y-%m-%d %H:%M:%S") #yyyy-MM-dd hh:mm:ss
File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\win32com\client\dynamic.py", line 686, in __setattr__
self._oleobj_.Invoke(entry.dispid, 0, invoke_type, 0, value)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The object does not support this method.', None, 0, -2147352567), None)
I am trying to create an Appointment using pywin32 and python. But the problem is that sometimes it works, and sometimes it does not like this code here, it seems like there is a problem that I could not see or hidden somewhere. The main issue here is that I am trying to fix the date problem (it turns to UTC+6 instead of UTC-6).
It seems you didn't format the date correctly. Try to use the following format:
"mm/dd/yyyy hh:mm AMPM"
Also it make sense to set the time zone first (before start and end of the meeting).

Flatlib use current date and time

Can someone help with me this?
I am using Flatlib to compute planet positions, but the code for entering the date and time for computation is fixed, so you have to update it each time.
Is there a way to using datetime.now() [or another way] to complete the fields in the Datetime() automatically? I can't get the code in the date = Datetime() to accept any form of datetime code.
I looking to get Datetime() to accept month/day/year and hour:minute:second format eg (08/24/2018, 21:17:00)
With the below code i get the following error:
C:\Users\famil>C:\Users\famil\Desktop\flatlib_working_degree.py
('{0.month}/{0.day}/{0.year}', '21:15:41')
Traceback (most recent call last):
File "C:\Users\famil\Desktop\flatlib_working_degree.py", line 13, in
date = Datetime(x)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 177, in init
self.date = Date(date, calendar)
File "C:\Users\famil\AppData\Local\Programs\Python\Python37-32\lib\site-packages\flatlib\datetime.py", line 76, in init
self.jdn = int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple'
from flatlib.datetime import Datetime
from flatlib.geopos import GeoPos
from flatlib.chart import Chart
from flatlib import const
import datetime
# set date and time to now
now = datetime.datetime.now()
x = '{0.month}/{0.day}/{0.year}, {0.hour}:{0.minute}:{0.second}'.format(now)
print(x)
date = Datetime(x)
pos = GeoPos('53n15', '2e31')
chart = Chart(date, pos, hsys=const.HOUSES_PLACIDUS, IDs=const.LIST_OBJECTS)
# calculate body and degree value
asc = chart.get(const.ASC)
print(asc, asc.lon)
sun = chart.get(const.SUN)
print(sun, sun.lon, sun.movement())
moon = chart.get(const.MOON)
Flatlib's Datetime demands 2 separate inputs for date and time, as you can check here: Github: flatlib/datetime.py
.
def __init__(self, date, time=0, utcoffset=0, calendar=GREGORIAN):
But your code has only datetime 1 argument, separated by comma. That's incorrect:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d, %H:%M"))
You should write it like this:
now = datetime.datetime.now()
date = Datetime(now.strftime("%Y/%m/%d"), now.strftime('%H:%M'))

Error in generating list of dates

I have a python script
import urllib2
from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(date,month,year):
today = date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
But i get this error-
Traceback (most recent call last):
File "test.py", line 17, in <module>
print generateDateList(4,12,2017)
File "test.py", line 11, in generateDateList
today = date(year, month, date)
TypeError: 'int' object is not callable
Why is it failing? I substituted the function with values and it worked. Should i convert the function inputs to integer again?
This line - def generateDateList(date,month,year):
The name of the first argument date shadows the name date imported at the top. You need to rename the argument to something like day inside your function.
As written, date is actually an integer you pass to the function, and calling it results in an error you are seeing.
Two options.
Option No.1 (import datetime):
import datetime
def generateDateList(date, month, year):
today = datetime.date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.datetime.strftime(today + datetime.timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4, 12, 2017)
Option No.2 (rename date parameter to day):
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(day,month,year):
today = date(year, month, day)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
The problem is the fact you have a parameter with the same name of the date() function.

Error always on line 102 of my code

So I am creating a module, and I am importing it to a python shell and running some stuff to make sure all features work and such.
For some reason every time I run the code, it gives the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
#anything can be here
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
So where the #anything can be here is, is whatever is on line 102 of my code. Originally line 102 was:
if isinstance(startindex,datetime.datetime):
and I got the error above. I put a quick print statement on line 102 to check and it gave the same error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ryansaxe/Desktop/Code/python/modules/pymaps.py", line 102, in url_maker
print 'Hello'
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
Is this some sort of bug? Why is it telling me there is an error with datetime on the line print 'Hello'?
Because it may be helpful, I will give you the function I am having trouble with since I have no clue how this is possible. I am keeping the print 'Hello' line so you can see where line 102 is:
def url_maker(latitudes,longitudes,times=None,color='red',label=' ',zoom=12,center=None,start=None,end=None,by=None,size='600x300'):
urls = []
import datetime
if isinstance(times[0],str) or isinstance(times[0],datetime.datetime):
from dateutil import parser
if isinstance(times[0],str):
times = [parser.parse(x) for x in times]
if isinstance(start,str):
startindex = parser.parse(start)
else:
startindex = start
if isinstance(end,str):
endindex = parse.parse(end)
else:
endindex = end
print 'Hello'
if isinstance(startindex,datetime.datetime):
startpos = between_times(times,startindex,by='start')
elif isinstance(startindex,int):
if isinstance(endindex,datetime.datetime):
startpos = between_times(times,endindex,by='end') - start
else:
startpos = start
else:
pass
if isinstance(endindex,datetime.datetime):
endpos = between_times(times,endindex,by='end')
elif isinstance(endindex,int):
if isinstance(startindex,datetime.datetime):
endpos = between_times(times,startindex,by='start') + end
else:
endpos = end
else:
pass
else:
times = range(1,len(latitudes) + 1)
if isinstance(start,int):
startpos = start
else:
startpos = None
if isinstance(end,int):
endpos = end
else:
endpos = None
if isinstance(by,str):
lat,lon,t = latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print lat
t,lats,lons = time_sample(t,by,lat,lon)
elif isinstance(by,int):
lats,lons,t = latitudes[startpos:endpos:by],latitudes[startpos:endpos:by],times[startpos:endpos:by]
else:
lats,lons,t= latitudes[startpos:endpos],latitudes[startpos:endpos],times[startpos:endpos]
print t
print len(t)
if center == None:
latit = [str(i) for i in lats]
longi = [str(i) for i in lons]
center = '&center=' + common_finder(latit,longi)
else:
center = '&center=' + '+'.join(center.split())
zoom = '&zoom=' + str(zoom)
for i in range(len(lats)):
#label = str(i)
x,y = str(lats[i]),str(lons[i])
marker = '&markers=color:' + color + '%7Clabel:' + label + '%7C' + x + ',' + y
url = 'http://maps.googleapis.com/maps/api/staticmap?maptype=roadmap&size=' + size + zoom + center + marker + '&sensor=true'
urls.append(url)
#print i
return urls,t
You are running with a stale bytecode cache or are re-running the code in an existing interpreter without restarting it.
The traceback code has only bytecode to work with, which contains filename and linenumber information. When an exception occurs, the source file is loaded to retrieve the original line of code, but if the source file has changed, that leads to the wrong line being shown.
Restart the interpreter and/or remove all *.pyc files; the latter will be recreated when the interpreter imports the code again.
As for your specific exception; you probably imported the datetime class from the datetime module somewhere:
from datetime import datetime
The datetime class does not have a datetime attribute, only the module does.

Categories

Resources