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 ?

4 Answers 4

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')

Sign up to request clarification or add additional context in comments.

1 Comment

%z is supported only since Python 3.2
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

Comments

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')

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.