0

My string is ,

str='2014-09-24T15:18:57+0000'

and I am trying to convert this string to valid datetime object. How to do that ?

What I tried is ,

>>> from datetime import datetime
>>> datetime.strptime(str,'%Y-%m-%dT%H:%M:%S')

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    datetime.strptime(str,'%Y-%m-%dT%H:%M:%S')
  File "C:\Python27\lib\_strptime.py", line 328, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains: +0000

But When I tried to change string to str='2014-09-24T15:18:57' it works fine,

>>> datetime.strptime('2014-09-24T15:18:57','%Y-%m-%dT%H:%M:%S')
datetime.datetime(2014, 9, 24, 15, 18, 57)

Whats wrong with +0000 , How to avoid first error ?

oyks
  • 11
  • 6

4 Answers4

2

How about adding to your pattern %z that stands for UTC offset in the form +HHMM or -HHMM (empty string if the the object is naive)

So the pattern will look like %Y-%m-%dT%H:%M:%S%z.

If you don't want the +0000 and it will always be in your str you can change your code to datetime.strptime(str[:-5],'%Y-%m-%dT%H:%M:%S')

Vizjerei
  • 1,000
  • 8
  • 15
0

Well you have a string and this pattern

2014-09-24T15:18:57+0000
%Y  -%m-%dT%H:%M:%S[    ]

And you're missing the +0000

Two options:

  1. Get rid of +0000
  2. Add something to your pattern
Vincent Beltman
  • 2,064
  • 13
  • 27
0

try this:

import datetime
dt_str='2014-09-24T15:18:57+0000'
new_dt = dt_str[:19]
dt = datetime.datetime.strptime(new_dt, '%Y-%m-%dT%H:%M:%S')
Avinash Garg
  • 1,374
  • 14
  • 18
0

Whats wrong with +0000 , How to avoid first error ?

+0000 is a UTC offset, you could use %z directive to parse it (since Python 3.2):

>>> from datetime import datetime
>>> time_string = '2014-09-24T15:18:57+0000'
>>> datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S%z')
datetime.datetime(2014, 9, 24, 15, 18, 57, tzinfo=datetime.timezone.utc)

%z is not available on older Python versions. If all timestamps have the same UTC offset +0000 then you could parse it as:

>>> datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S+0000')
datetime.datetime(2014, 9, 24, 15, 18, 57)

Notice: the value is a naive datetime object (no timezone info). To attach the tzinfo, for older Python versions, see How to parse dates with -0400 timezone string in python?

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670