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?
-
How many other types of strings are there? Is datetime.datetime the only one, or do other class names appear?aghast– aghast2017年03月31日 21:26:16 +00:00Commented Mar 31, 2017 at 21:26
-
import datetime and then date = eval(a)plasmon360– plasmon3602017年03月31日 21:26:53 +00:00Commented Mar 31, 2017 at 21:26
3 Answers 3
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
2 Comments
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)
3 Comments
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.you could use eval. eval lets run python code within python program
a = "datetime.datetime(2009,04,01)"
import datetime
a = eval(a)
print a
print type(a)
will result in
2009年04月01日 00:00:00
<type 'datetime.datetime'>