Search code examples
python-2.7datetimestrptime

datetime.strptime() returns a formatting error with %f


I am currently trying to convert a number of seconds into minutes and seconds notation. I am using divmod and trying to turn the result into a datetime value. I have the following code:

from datetime import datetime, timedelta
processtime = 69.009
m, s = divmod(processtime, 60)
m= str(m)
m=m[:1]
s= str(s)
s=s[:5]
processstring= m+ ' ' + s
datetimeprocess = datetime.strptime(processstring, "%M %S.f")

However every time i do this I get this error:

ValueError: time data '1 9.009' does not match format '%M %S.f'

I'm fairly sure I have matched the format and I can't figure out what the problem is.


Solution

  • You're missing a % before f:

    datetimeprocess = datetime.strptime(processstring, "%M %S.%f")
    

    Test results:

    >>> from datetime import datetime, timedelta
    >>> processstring = '1 9.009'
    >>> datetimeprocess = datetime.strptime(processstring, "%M %S.%f")
    >>> print datetimeprocess
    1900-01-01 00:01:09.009000
    >>>