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

Community
  • 1
  • 1
Robert
  • 191
  • 1
  • 2
  • 4
  • 2
    Step 1. Search. Step 2. Read. Step 3. Close. – S.Lott Jul 15 '11 at 12:41
  • possible duplicate of [Parse date and format it using python?](http://stackoverflow.com/questions/2265357/parse-date-and-format-it-using-python) and http://stackoverflow.com/questions/1713594/parsing-dates-and-times-from-strings-using-python and numerous others. – S.Lott Jul 15 '11 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... – Mu Mind Oct 05 '12 at 07:34
  • Possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – Mu Mind Oct 05 '12 at 07:39

2 Answers2

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")
Community
  • 1
  • 1
Mu Mind
  • 10,935
  • 4
  • 38
  • 69
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

Andrew Walker
  • 40,984
  • 8
  • 62
  • 84
  • Could you please give an example, like considering the string above. Thanks :) – Robert Jul 15 '11 at 12:41
  • 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 ? – Robert Jul 15 '11 at 12:55
  • The dateutil.parser worked for me. I have not been successful with the strptime. It just doesn't seem to work on Windows XP? – user595985 Oct 20 '11 at 09:36