I have a string like
a = "datetime.datetime(2009,04,01)"
I would like to convert this to a datetime object in python. How should I proceed?
I have a string like
a = "datetime.datetime(2009,04,01)"
I would like to convert this to a datetime object in python. How should I proceed?
The code in the previous answer would work, but using eval is considered risky, because an unexpected input could have disastrous consequences. (Here's more info on why eval can be dangerous.)
A better option here is to use Python's strptime method:
from datetime import datetime
datetime_string = "datetime.datetime(2017, 3, 31)"
format = "datetime.datetime(%Y, %m, %d)"
datetime_object = datetime.strptime(datetime_string, format)
There are lots of different formats you can use for parsing datetimes from strings. You may want to check out the docs: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
eval also because it's clear about exactly what it's trying to do. With eval, you would have to read the surrounding code to understand what's happening, which can make debugging hard later on.You can use eval
eval('datetime.datetime(2009, 1, 1)')
You'll have to make sure datetime is imported first
>>> import datetime
>>> d = datetime.datetime(2009, 1, 1)
>>> repr(d)
'datetime.datetime(2009, 1, 1, 0, 0)`
>>> eval(repr(d))
datetime.datetime(2009, 1, 1, 0, 0)
eval. It's just that historically eval-type functionality has been used to run arbitrary statements from users. There really just aren't many use cases for eval. If you're using it, there's probably a much better and safer way to do what you want to accomplish without eval.datetime.strptime, the worst that can happen is that you get a wrong month/day. With eval, you could lose control of your server.