Error in generating list of dates - python

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.

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.

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'))

Why am I getting the error: 'method_descriptor' object has no attribute 'now'?

If I run the method
from datetime import datetime
from timedelta import time
def action_retbook(self, cr, uid, ids, context=None):
dt = datetime.date.now()
todaydate = datetime.strptime(dt, "%y/%m/%d")
x=6
cr.execute("""update rmkbook_issue set dt_of_return ='%s' where id= %s """ %(todaydate, x))
return
I get the error 'method_descriptor' object has no attribute 'now'. Why?
You can run the method now() like this:
dt = datetime.now()
You can check this question as well
I believe
from datetime import datetime
datetime.now()
Works.. in python 3.9.7

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']

python debug straightforward datetime object

I cannot understand why this is failing, can someone please explain:
import datetime
def test(timestamp):
xt = datetime(2013, 4,4)
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
The error is:
Traceback (most recent call last):
File "", line 12, in
File "", line 5, in test
TypeError: 'module' object is not callable
It seems to work ok with from datetime import datetime instead. I can't understand what the difference is.
Thanks.
Because in the datetime module, there is a datetime() function, but you didn't call it ( you instead tried to call the module, that's why you got a TypeError: 'module' object is not callable).
import datetime
def test(timestamp):
xt = datetime(2013, 4,4) # Problem is this line.
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
To fix the line, change it to:
xt = datetime.datetime(2013,4,4)
The reason from datetime import datetime worked was because you imported the specific function, and so you wouldn't need to do datetime.datetime().
datetime is both a module AND a class in that module. In your example you need datetime.datetime.
The
xt = datetime(2013, 4,4)
should be
xt = datetime.datetime(2013, 4,4)
Here, datetime is the name of the module. The full name of the class is datetime.datetime.
datetime is the datetime module, datetime.datetime is the datetime type:
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
Here datetime can refer to the module or the class within the module so you have to disambiguate
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
gives the following output:
(datetime.datetime(2013, 4, 4, 0, 0), datetime.datetime(2013, 4, 4, 8, 37, 20))

Categories

Resources