Line 84 in lstToDt() method, I tried to convert 'i' which takes a string datetime from list to datetime object but:
when I use datetime.datetime.strftime(i,"format") an error comes that i is a string object and not datetime.datetime.
When I use datetime.datetime.strptime(i,"format") an error comes that i is a datetime.datetime and not string.
Code :
def lstToDt(lt): # Converts list string elements into Dates
for i in lt:
i = datetime.datetime.strftime(i,"%Y-%m-%d")
lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
return lt
Errors :
i = datetime.datetime.strftime(i,"%Y-%m-%d")
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'
lt.append(datetime.datetime.strptime(i,"%Y-%m-%d"))
TypeError: strptime() argument 1 must be str, not datetime.datetime
What is happening? Can anyone help please?
You have passed string value to strptime, that is not acceptable for python,
def lstToDt(lt): # Converts list string elements into Dates
for i in lt:
j = datetime.datetime.strptime(i,"%Y-%m-%d")
lt.append(datetime.datetime.strptime(j,"%Y-%m-%d"))
return lt
This should work!
Hope this helps!
Related
I'm trying to add a check here that if the receiver is just a string. then convert that into list else just pass.
if type(receiver) == str:
receiver=[receiver]
error:
TypeError: 'str' object is not callable
You can check the type of an instance with the following.
if isinstance(receiver, str):
# do something if it is a string
If you just need to check rather it is not a string:
if not isinstance(receiver, str):
# do something if it is not a string
Look at this tutorial to learn more about the function.
a = '123'
print(str(a))
print(type(a))
I used this code in google collab to ask user for input date
but on execution of the code I get
TypeError: 'str' object is not callable
from datetime import datetime
date_entry = input('Enter a date (i.e. 2017,7,1)')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)
I am not calling any string, what is wrong?
Python has several function (int, input, map, list, set, dict, min, max, ...) as build ins that you use in your code.
Those functions have names that are not protected from being used otherwise. Using them as variable names however hides the original function from being accessed.
Doing so leads to this kind of error message.
Demo:
from datetime import datetime
# store the original functions under different name for restoring them later
old_int = int
old_map = map
old_input = input
old_dt = datetime
for what in ["int", "map", "input", "datetime"]:
# restore original functions to their names
int, map, input, datetime = old_int, old_map, old_input, old_dt
# set current function to be a string
if what == "int":
int = "some string"
elif what == "map":
map = "some string"
elif what == "input":
input = "some string"
else:
datetime = "some string"
print(f"The '{what}' function was overwritten to be a string")
# try to use the overwritten function and print the error message if it happens
try:
date_entry = input('Enter date: ')
year, month, day = map(int, date_entry.split(','))
date = datetime(year, month, day)
except Exception as e:
print(e, "\n")
Output:
The 'int' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'map' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The 'input' function was overwritten to be a string
'str' object is not callable
The 'datetime' function was overwritten to be a string
Enter date: 2021,2,2
'str' object is not callable
The code is correct. it's the issue of indentation.
When I print a numpy.timedelta64 scalar using string formatting I get a TypeError.
In [10]: td = np.timedelta64(5410102,'us')
In [12]: td.ndim # check td is really a scalar
Out[12]: 0
In [13]: print("td: {}".format(td))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-bae2acf5773a> in <module>
----> 1 print("td: {}".format(td))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
In [14]: print("td: {!r}".format(td)) # printing using repr() works as expected
td: numpy.timedelta64(5410102,'us')
In [15]: print(td) # Just printing also works fine
5410102 microseconds
Any ideas what's going on?
Update:
The error seems to be in the numpy.timedelta64.__format__() function.
In [67]: td.__format__("")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-67-6acc460ea008> in <module>
----> 1 td.__format__("")
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
It just seems a bug to me. A work around is to convert it to string before formatting.
In [68]: print("{}".format(str(td)))
5410102 microseconds
You can read about datetime.timedelta function here. Anyways, it says that this function return an instance of a Date object.
The error appears because you can't concatenate a string with an object.
In order to solve this problem, you need to concatenate the string with a printable representation of the object using one of the follwing ways:
print(str + str(object)) # In this case, turns to the toString() function of the object, if exists (otherwise it returns an error). Converts the text the object shows to a string. In this case, it's possible to use that method on Date instances.
print(str + repr(object) # repr() functions returns a printable representation of the object of their class.
By the way, the line print(object) works because it turns to the toString() function of the object. Using print(str + object) is forbidden because it tries to print a non-concatenative variables which is not possible, as explained.
Given the following pandas series:
s = pd.Series(dict(A = np.zeros(100), B = np.zeros(100), C = None))
How can I replace the last element with the object np.zeros(100)? In the real case, I have a very long Series and want to replace all None objects in a similar way.
So far, I tried:
s.fillna(np.zeros(100))
ValueError: invalid fill value with a <type 'numpy.ndarray'>
s.replace(None, np.zeros(100))
TypeError: 'regex' must be a string or a compiled regular expression or a list or dict of strings or regular expressions, you passed a 'bool'
s.fillna(np.NaN).replace(np.NaN, np.zeros(100))
TypeError: Invalid "to_replace" type: 'float'
My python UDF code, born is a datetime variable from Pig ,
I tried it as string object but it also gave an error,
and treating it as a datetime object also gave an error
from datetime import date
#outputSchema("age_key:chararray")
def agekeyed(born):
today = date.today()
return born[:4]
I get an error :
TypeError: 'org.joda.time.DateTime' object is unsubscriptable
at org.python.core.Py.TypeError(Py.java:235)
at org.python.core.PyObject.__finditem__(PyObject.java:585)
at org.python.core.PyObjectDerived.__finditem__(PyObjectDerived.java:861)
at org.python.core.PyObject.__getitem__(PyObject.java:653)
at org.python.core.PyObjectDerived.__getitem__(PyObjectDerived.java:901)
at org.python.core.PyObject.__getslice__(PyObject.java:740)
at org.python.core.PyObjectDerived.__getslice__(PyObjectDerived.java:924)
at org.python.pycode._pyx3.agekeyed$1(keying.py:6)
at org.python.pycode._pyx3.call_function(keying.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
at org.python.core.PyFunction.function___call__(PyFunction.java:376)
at org.python.core.PyFunction.__call__(PyFunction.java:371)
at org.python.core.PyFunction.__call__(PyFunction.java:361)
at org.python.core.PyFunction.__call__(PyFunction.java:356)
at org.apache.pig.scripting.jython.JythonFunction.exec(JythonFunction.java:117)
... 16 more
born is a org.joda.time.DateTime object, and substring cannot be applied here.
You need to pass a chararray from pig to the udf, or deal with the object with it's methods
rightnow.monthOfYear().getAsText()