Problem with cycled import in datetime in python - 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.

Related

json.dumps gives me AttributeError: 'str' object has no attribute 'get'

I am getting this error message:
AttributeError: 'str' object has no attribute 'get'
I know that it is my json.dumps that triggers the error. Here is my code:
from django.http import HttpResponse
import os
import datetime
import json
SUNDAY = 6
SATURDAY = 5
weekdayBookingTimes = ["10:00","10:30","11:00","11:30","12:00", "12:30", "13:00","13:30", "14:00", "14:30", "15:00", "15:30", "16:00", "16:30", "17:00", "17:30", "18:00"]
def sendBookingForDate(request):
dateToFetchBookings = request.GET.get('date','')
#Check if date is SUNDAY
if checkDayOfWeek(dateToFetchBookings) == SUNDAY:
pass
#Check if day is Saturday
elif checkDayOfWeek(dateToFetchBookings) == SATURDAY:
if os.path.isfile((dateToFetchBookings+".txt")):
pass #tbt
else:
createBookingsForSaturday(dateToFetchBookings)
#Check if day is normal day
else:
if os.path.isfile(dateToFetchBookings+'.txt'):
pass
else:
createBookingsForNormalDays(dateToFetchBookings)
with open('/home/MScissorss/mysite/mysite/'+dateToFetchBookings+'.txt') as f:
bookingsToSend = json.load(f)
#return HttpResponse(dateToFetchBookings)
return json.dumps(bookingsToSend)
def checkDayOfWeek(date):
tempDateStorage = date.split('-')
year = int(tempDateStorage[0])
month = int(tempDateStorage[1])
day = int(tempDateStorage[2])
return datetime.datetime(year,month,day).weekday()
def createBookingsForSaturday(date):
normalBookings = {}
for x in range(0,11):
normalBookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}
with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
file.write(json.dumps(normalBookings))
def createBookingsForNormalDays(date):
#Test data
bookings = {}
for x in range(0,17):
bookings[x] = {"bookingTime":weekdayBookingTimes[x], "booked":"false", "bookieName":"", "bookieNumber":""}
with open('/home/MScissorss/mysite/mysite/'+date+'.txt', "w") as file:
file.write(json.dumps(bookings))
Check the end of the first function. That is where i do the return. I also thought that my dictionary was wrongly formatted, but i checked and it looks good:
{
"0": {"bookingTime": "10:00", "booked": "false", "bookieName": "", "bookieNumber": ""},
"1": {"bookingTime": "10:30", "booked": "false", "bookieName": "", "bookieNumber": ""},
"2": {"bookingTime": "11:00", "booked": "false", "bookieName": "", "bookieNumber": ""},
"3": {"bookingTime": "11:30", "booked": "false", "bookieName": "", "bookieNumber": ""}
}
The return that is commented above json.dumps works well. I get no errors when running that. Any ideas on what the problem could be?
UPDATE - Full traceback added
2018-11-15 23:53:05,718: Internal Server Error: /getBookings/
Traceback (most recent call last):
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/utils/deprecation.py", line 93, in __call__
response = self.process_response(request, response)
File "/home/MScissorss/.virtualenvs/django2/lib/python3.7/site-packages/django/middleware/clickjacking.py", line 26, in process_response
if response.get('X-Frame-Options') is not None:
AttributeError: 'str' object has no attribute 'get'
As #Barmar pointed out in the comments. All i needed to do was to change my return from return json.dumps(bookingsToSend) to return JsonResponse(bookingsToSend)

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.

Odoo Import Libaray

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.

Python - an identical line of code using datetime fails in one file but not another

I have the following lines of code in project A
#filename : mod_dates
#Handles date calculations etc
import datetime
class datecalcs:
def __init__(self):
self.__menuChoice = 0
self.__datemonth = "not set"
self.__effectivedate = ""
self.__year = 0
self.__month = 0
return None
#
def interestcouponpaydates(self,effectivedate,couponday):
self.__effectivedate = effectivedate
year, month, day = map(int,self.__effectivedate.split('-'))
print(year)
print(month)
return self.__effectivedate
When I call them from another file with
import mod_dates
import datetime
import modcalinputs
datesclass = mod_dates.datecalcs()
calcInputs = modcalinputs.calcinputs()
#Get the coupon date
interestdateeffective = calcInputs.interestdateffective()
interestdatecoupon = calcInputs.interestdatecoupon()
x = datesclass.interestcouponpaydates(interestdateeffective,interestdatecoupon)
print(x)
However this returns an error on the x = datesclass... line of
year, month, day = map(int,self.__effectivedate.split('-'))
raises:
> AttributeError: 'datetime.date' object has no attribute 'split'
When I run from a similar project to the same line with the same syntax it works fine. Any ideas on what I am doing wrong?
Looks like something is assigning a datetime.date object to __effectivedate. You can't call split() on that:
>>> import date
>>> d = d = datetime.date(2012,3,12)
>>> d.split('-')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'split'
You can convert it to a string and split:
>>>str(d).split('-')
['2012', '03', '12']

Categories

Resources