Lucas Kauffman
Lucas Kauffman

Reputation: 6891

Formatting with time.strptime() throws an error

I'm trying to convert the following date (which is a string) to a datetime object:

Fri, 26 Apr 2013 12:00:00 +0000

So what I did is throw the +0000 value out and then convert it to a datetime object using the following code:

published = entry['published']
print published
published = published[:-6]
print published
published = time.strptime("%a, %d %b %Y %H:%M:%S",str(published))

Which then throws an exception saying the given value is not in the right format

Fri, 26 Apr 2013 12:00:00 +0000
Fri, 26 Apr 2013 12:00:00
        C:\Python27\python.exe 
    C:/obfuscated.py
        Traceback (most recent call last):
        Fri, 26 Apr 2013 12:00:00 +0000
          File "C:/obfuscated.py", line 17, in <module>
        Fri, 26 Apr 2013 12:00:00
            class MyClass(object):
          File "C:/obfuscated.py", line 38, in MyClass
            published = time.strptime("%a, %d %b %Y %H:%M:%S",str(published))
          File "C:\Python27\lib\_strptime.py", line 467, in _strptime_time
            return _strptime(data_string, format)[0]
          File "C:\Python27\lib\_strptime.py", line 325, in _strptime
            (data_string, format))
        ValueError: time data '%a, %d %b %Y %H:%M:%S' does not match format 'Fri, 26 Apr 2013 12:00:00'

I'm not sure why this fails as the datetime stringformat seems right to me.

Upvotes: 0

Views: 843

Answers (1)

stonesam92
stonesam92

Reputation: 4457

You have the parameters round the wrong way, the format string should be the second argument.

Try:

published = time.strptime(str(published),"%a, %d %b %Y %H:%M:%S")

Upvotes: 1

Related Questions