TheBigOnion TheBigOnion - 10 months ago 136
Python Question

unconverted data remains: .387000 in Python

I have a datetime that is a string I read from a text file. I want to trim the extra milliseconds off of it, but I want to convert it to a datetime variable first. This is because it may be in different formats depending on what is in the text file. How ever, everything I have tried wants me to already know the format. Please take a look at what I am trying here:

import time, datetime

mytime = "2015-02-16 10:36:41.387000"
myTime = time.strptime(mytime, "%Y-%m-%d %H:%M:%S.%f")

myFormat = "%Y-%m-%d %H:%M:%S"

print datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, myFormat)))

But this gives me this error:

File "python", line 10, in <module>
ValueError: unconverted data remains: .387000`

Can someone please tell me how to do a normal datetime format? In other languages I can pass in various formats and then set it to a new format without a problem.

Answer Source

You are doing it backwards. Try this:

from datetime import datetime

mytime = "2015-02-16 10:36:41.387000"
myTime = datetime.strptime(mytime, "%Y-%m-%d %H:%M:%S.%f")

myFormat = "%Y-%m-%d %H:%M:%S"

print "Original", myTime
print "New", myTime.strftime(myFormat)


Original 2015-02-16 10:36:41.387000
New 2015-02-16 10:36:41