2

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?

2
  • How many other types of strings are there? Is datetime.datetime the only one, or do other class names appear? Commented Mar 31, 2017 at 21:26
  • import datetime and then date = eval(a) Commented Mar 31, 2017 at 21:26

3 Answers 3

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

I prefer this code over 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.
Thanks a lot. That fixed it!!
0

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

@PatrickHaugh Well, running any untrusted code is dangerous, with or without 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.
Nope. With datetime.strptime, the worst that can happen is that you get a wrong month/day. With eval, you could lose control of your server.
-1

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'>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.