0

I want to convert the following string to date in python ,how to go about this,

>>> d= "1997-01-29 00:00:00+00:00"
>>> import datetime
>>> datetime.datetime.strptime(d, '%Y-%m-%d').date()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:  00:00:00+00:00
Rajeev
  • 44,985
  • 76
  • 186
  • 285
  • Either slice up the input, or use a format that *actually represents the data you're parsing*. – jonrsharpe Oct 09 '15 at 12:56
  • What version of python? – sbarber2 Oct 09 '15 at 13:04
  • python strptime isn't going to like the colon in the time zone offset piece. Have a look at [Converting string to datetime object in python](http://stackoverflow.com/questions/2609259/converting-string-to-datetime-object-in-python) – sbarber2 Oct 09 '15 at 13:05
  • Also, what date is it that you want? The date part from the literal text of the string (in which case you could just parse for the space and ignore the rest of the string)? Or do you need to figure out what day the point in time represented by that datetime-ish string would occur in on the machine that is executing this bit of code (in which case you need to consider the whole thing including the timezone offset)? – sbarber2 Oct 09 '15 at 13:19
  • Answering my own question: python 2.7. Right, python strptime can't directly handle timezone offsets in this format. See the linked answer above for workaround ideas. But I think you should clarify your requirements more first before deciding on an implementation. – sbarber2 Oct 09 '15 at 13:23

2 Answers2

0

The error is pretty explicit in stating that you have an uncovered portion of your string that wasn't expected based on what you are trying to convert.

You have provided this:

d = "1997-01-29 00:00:00+00:00"

You are trying to convert based on this pattern:

'%Y-%m-%d'

The error is stating:

ValueError: unconverted data remains:  00:00:00+00:00

So, you should simply strip off that time portion based on how you are converting. I simply changed your string to this and it worked:

>>> d= "1997-01-29"
>>> datetime.datetime.strptime(d, '%Y-%m-%d').date()
datetime.date(1997, 1, 29)
idjaw
  • 25,487
  • 7
  • 64
  • 83
0
d= "1997-01-29 00:00:00"
import datetime
print datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
Anurag Verma
  • 485
  • 2
  • 12