AttributeError: 'str' object has no attribute 'Substr' - python

I'm writing a python script to convert data from csv to geojson, which is working.
I have a field in the date format ( "2017-07-14 17:01:00") but fro this data I only need the hours part (17 only) so I'm trying to substring it to get only that part, I added that function:
def substr(strtime):
strtime = strtime.Substr(strtime, 0, 3)
return substr(strtime)
And I'nm getting that error meaage
AttributeError: 'str' object has no attribute 'Substr'
Does any body have an idea about how to fix it?

Strings in python can be treated as char arrays so you can access like this:
myStr=strtime[0:3]

Use datetime module.
Ex:
import datetime
def substr(strtime):
strtime = datetime.datetime.strptime(strtime, "%Y-%m-%d %H:%M:%S")
return strtime.strftime("%H")
print( substr( "2017-07-14 17:01:00") )
If you do not want to use datetime module you can do.
def substr(strtime):
return strtime[11:13]
Output:
17

Related

Type Error: can only concatenate str (not "float") to str

My Error is:
web.open("https://web.whatsapp.com/send?phone=" +lead+ "&text=" +message)
TypeError: can only concatenate str (not "float") to str
I am trying to automate the Whatsapp message and it shows this error. I am not able to understand what it means.
import pyautogui as pg
import webbrowser as web
import time
import pandas as pd
data = pd.read_csv("phone numbers.csv")
data_dict = data.to_dict('list')
leads = data_dict['Number']
messages = data_dict['Message']
combo = zip(leads,messages)
first = True
for lead,message in combo:
time.sleep(4)
web.open("https://web.whatsapp.com/send?phone="+lead+"&text="+message)
if first:
time.sleep(6)
first=False
width,height = pg.size()
pg.click(width/2,height/2)
time.sleep(8)
pg.press('enter')
time.sleep(8)
pg.hotkey('ctrl', 'w')
You need to convert lead to it's string representation first:
web.open("https://web.whatsapp.com/send?phone="+str(lead)+"&text="+message)
The error you are seeing is because your leadvariable is a number, or float type of variable, not a string.
"Concatenate" is what you are trying to do with the + in the web.open line of code - you are generating a new string by adding multiple strings together.
However, Python doesn't allow you to concatenate a number or other non-string type to a string without explicitly converting it first.
web.open("https://web.whatsapp.com/send?phone="+str(lead)+"&text="+message)

How to print only if specific time starts with x in Python

Hi I'm a newbie learning python and I want to print something only if current time starts with x (for example, if current time starts with = 4, print "hi", time = 4:18), this is the code I made, it says attribute error:
import datetime
local = datetime.datetime.now().time().replace(microsecond=0)
if local.startswith('16'):
print("Hi! It's ", local)
The .replace() method returns a date object. date objects don't have a .startswith() method. That method is only for str.
Try converting your date to a string first:
if str(local).startswith('16'):
print("Hi! It's ", local)
The documentation lists all of the methods available on a date object.
You need to first convert it to a string, as datetime objects have no startswith() method. Use strftime, example:
import datetime
t = datetime.datetime(2012, 2, 23, 0, 0)
t2 = t.strftime('%m/%d/%Y')
will yield:
'02/23/2012'. Once it's converted, you can use t2.startswith().
https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
You can get the hour of the time and check if it is 16:
if local.hour == 16:
print("Hi! It's ",local)
If you need to use startswith() then you can convert it to a string like this:
if str(local).startswith('16'):
print("Hi! It's ", local)
That's not a good way. Check the time as int is the better solution here.
replace() has 2 needed str arguments. You use a named attribute which doesn't exist.

How do I use variable inside a parentheses and single quotes?

Using Python 2.7 I am trying to put a variable inside a (' ')
Orignial string
r = search.query('Hello World')
What I have tried so far and is not working...
r = search.query('{0}').format(company_name_search)
r = search.query('s%') % (company_name_search)
Both methods are not working and output the error below. What is the best way to take r = search.query('Hello World') and put a variable for Hello World so I can dynamically change the search parameters at will?
AttributeError: 'Results' object has no attribute 'format'
TypeError: unsupported operand type(s) for %: 'Results' and 'str'
You are now applying the .format() or % to the query(). Apply them to the string. '{0}'.format(company_name_search) or '%s'%(company_name_search). Then throw that into the query function, like
r = search.query('{0}'.format(company_name_search))
r = search.query('s%' % (company_name_search))

Not able to convert to string

I might be using wrong python terminology.
I have an array of 3 integer elements: month, date and year.
However, I am not able to print each individual element when concatenating strings.
import ssl
import OpenSSL
import time
import sys
def get_SSL_Expiry_Date(host, port):
cert = ssl.get_server_certificate((host, 443))
x509 = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, cert)
raw_date = x509.get_notAfter()
decoded_date = raw_date.decode("utf-8")
dexpires = time.strptime(decoded_date, "%Y%m%d%H%M%Sz")
bes = dexpires.tm_mon,dexpires.tm_mday,dexpires.tm_year
print (bes)
#print(bes[0]+"/"+bes[1]+"/"+bes[2])
domain = sys.argv[1]
port = 443
get_SSL_Expiry_Date(domain, port)
If I uncomment line 14, I get an error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I am trying to get the date in this format (all strings): Month/Date/Year.
What am I doing wrong?
You can use Python's format() method to handle it (much cleaner also):
print("{0}/{1}/{2}".format(bes[0],bes[1],bes[2]))
...or further simplified (thanks Anton)
print("{0}/{1}/{2}".format(*bes))
↳ Python String Formatting
Simply use:
print(time.strftime("%m/%d/%y",dexpires))
See also https://docs.python.org/3/library/time.html
In general python modules usually contain all kinds of reformatting functions you don't have to reinvent them.
Example:
>>> dexpires=time.strptime('20180823131455z','%Y%m%d%H%M%Sz')
>>> dexpires
time.struct_time(tm_year=2018, tm_mon=8, tm_mday=23, tm_hour=13, tm_min=14, tm_sec=55, tm_wday=3, tm_yday=235, tm_isdst=-1)
>>> time.strftime('%m/%d/%y',dexpires)
'08/23/18'
>>>
First you have to convert int values to string than only you are able to concave them.
You can use str() inbuilt method
print(str(bes[0])+"/"+ str(bes[1])+"/"+ str(bes[2])) #convert int to str first.

TypeError: 'int' object is unsubscriptable

In python I get this error:
TypeError: 'int' object is unsubscriptable
This happens at the line:
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
I couldn't find a good definition of unsubscriptable for python anywhere.
for quote in sector[singlestock]:
i+=1
if i < len(sector):
if i==0:
sectorcalc[i][0]= quote[0]
sectorcalc[i][2]= 0
sectorcalc[i][3]= 0
sectorcalc[i][4]= 0
sectorcalc[i][5]= 0
sectorcalc[i][6]= 0
sectorcalc[i][7]= 0
else:
yesterday = sector[singlestock-1][i]
print yesterday
today = quote
print type(today[2])
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
sectorcalc[i][3]= (today[3]/yesterday[3])-1
sectorcalc[i][4]= (today[4]/yesterday[4])-1
sectorcalc[i][5]= (today[5]/yesterday[5])-1
sectorcalc[i][6]= (today[6]/yesterday[6])-1
sectorcalc[i][7]= (today[7]/yesterday[7])-1
What does this error mean?
The "[2]" in today[2] is called subscript.
This usage is possible only if "today"
is a sequence type. Native sequence
types - List, string, tuple etc
Since you are getting an error - 'int' object is unsubscriptable. It means that "today" is not a sequence but an int type object.
You will need to find / debug why "today" or "yesterday" is an int type object when you are expecting a sequence.
[Edit: to make it clear]
Error can be in
sectorcalc[i]
today (Already proved is a list)
yesterday
This is confusing to read:
today = quote
Is today = datetime.date.today()? Why would a date suddenly refer to a quote? Should the variable name be quoteForToday or something more expressive? Same for yesterday. Dividing two dates as you do makes no sense to me.
Since this is a quote, would today and yesterday refer to prices or rates on different days? Names matter - choose them carefully. You might be the one who has to maintain this six months from now, and you won't remember what they mean, either.
Not that the code you wrote is valid, but I can't see why you wouldn't use a loop.
for j in range(2,7):
sectorcalc[i][j] = (today[j]/yesteday[j])-1
instead of
sectorcalc[i][2]= ((today[2]/yesterday[2])-1)
sectorcalc[i][3]= (today[3]/yesterday[3])-1
sectorcalc[i][4]= (today[4]/yesterday[4])-1
sectorcalc[i][5]= (today[5]/yesterday[5])-1
sectorcalc[i][6]= (today[6]/yesterday[6])-1
sectorcalc[i][7]= (today[7]/yesterday[7])-1
How to reproduce that error:
myint = 57
print myint[0]
The people who wrote the compiler said you can't do that in the following way:
TypeError: 'int' object is unsubscriptable
If you want to subscript something, use an array like this:
myint = [ 57, 25 ]
print myint[0]
Which prints:
57
Solution:
Either promote your int to a list or some other indexed type, or stop subscripting your int.

Categories

Resources