Why this is achieved by repr method only?
import datetime
d=datetime.datetime.now()
x=str(d)
y=eval(x)
print(y)
It's showing
SyntaxError: invalid token
Why this is achieved by repr method only?
import datetime
d=datetime.datetime.now()
x=str(d)
y=eval(x)
print(y)
It's showing
SyntaxError: invalid token
When you call str(datetime.datetime.now()), you get a string representing the current time such as 2019-07-08 19:32:04.078030.
But when repr(datetime.datetime.now()) is called, the actual format of the datetime object is returned. Something like datetime.datetime(2019, 7, 08, 19, 32, 4, 78030).
eval() evaluates the string as a python function. since 2019-07-08 19:32:04.078030 is not a python command, you get an error. datetime.datetime(2019, 7, 08, 19, 32, 4, 78030) however is a python command and is executed.
Overall the programs that will work are
Using str():
import datetime
d=datetime.datetime.now()
x=str(d)
print(x)
Using repr():
import datetime
d=datetime.datetime.now()
x=repr(d)
y=eval(x)
print(y)