0

How can I get this string in the format "%Y-%m-%d %H:%M:%S"?

myDateTime = 'datetime.datetime(2012, 11, 16, 3, 0)'

I have tried:

x = myDateTime.strftime("%Y-%m-%d %H:%M:%S")

and I get the error:

"Attribute Error: 'str' object has no attribute 'strftime'".

I also tried using strptime but myDateTime is not of type datetime.

My objective is to get the string to be interpreted verbatim then I would have a datetime object that I could work with.

1
  • 1
    mm-dd-yy is a terrible format. If mdy order is used, it is better to use /, with dmy, it should better be a . and ymd, the one to be favourized, is delimited with -. Commented Nov 13, 2012 at 9:31

1 Answer 1

4

Your object mydatetime is surrounded by quotes: it's a string. Just drop the quotes:

myDateTime = datetime.datetime(2012, 11, 16, 3, 0)
myDatetime.strftime("%Y-%m-%d %H:%M:%S")

If mydatetime is the output of a function that returns a string (such as your SQL query), you could try to use eval to transform it into a regular Python object. BE VERY CAREFUL, though, as eval is not secure at all. You may want to use the third-party module asteval instead.

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

1 Comment

Thank you Pierre. It is indeed the output of the SQL query. I'll play around with asteval and see if I can get that to take care of my issue. I'll have to upgrade my version of Python as I'm still on 2.5 and asteval does not support it. I'll get to that and check back in when I'm finished.

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.