Scott Skiles
Scott Skiles

Reputation: 3847

Converting a String to Datetime and back to a String with a Different Format

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.

Upvotes: 0

Views: 5493

Answers (1)

Pierre GM
Pierre GM

Reputation: 20339

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.

Upvotes: 4

Related Questions