3

Possible Duplicate:
Parse date and format it using python?

i have a date string like 2011-07-15 13:00:00+00:00 . Any way to convert this string to a datetime object in python ?

Thank You

4
  • 3
    Step 1. Search. Step 2. Read. Step 3. Close. Commented Jul 15, 2011 at 12:41
  • possible duplicate of Parse date and format it using python? and stackoverflow.com/questions/1713594/… and numerous others. Commented Jul 15, 2011 at 12:43
  • Really would be better to at least mark this as a duplicate of a date_time_-related question, not date. Both of the questions linked are for dates, which may have some different answers... Commented Oct 5, 2012 at 7:34
  • Possible duplicate of Converting string into datetime Commented Oct 5, 2012 at 7:39

2 Answers 2

11

You can handle the time zone appropriately, and have the format recognized automatically, if you use dateutil.parser, as described here:

from dateutil import parser
dt = parser.parse("2011-07-15 13:00:00+00:00")
Sign up to request clarification or add additional context in comments.

Comments

4

You can use the strptime function in the datetime module. http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior

datetime.datetime.strptime('2011-07-15 13:00:00', '%Y-%m-%d %H:%M:%S')

Edit:

Lesson learnt, the datetime module isn't capable of doing this, at least on my platform. Mu Mind's solution seems to be the easiest way to do this robustly according to http://wiki.python.org/moin/WorkingWithTime

3 Comments

Could you please give an example, like considering the string above. Thanks :)
Thanks for the reply when i do datetime.datetime.strptime('2011-07-15 13:00:00+00:00', '%Y-%m-%d %H:%M:%S') im getting 'ValueError: unconverted data remains: +00:00' :( . Is there some error in my format string ?
The dateutil.parser worked for me. I have not been successful with the strptime. It just doesn't seem to work on Windows XP?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.