Snowman
Snowman

Reputation: 32061

Python datetime precision

I have a Google App Engine datetime property which I populate with x.date = datetime.datetime.now(). I do a lot of comparisons between dates, and after much debugging, it turns out my client device sends dates out with less precision than a Python date, which caused a terrible mess.

Here is what Python generates: 2012-08-28 21:36:13.158497 with datetime.datetime.now(), but what I want is 2012-08-28 21:36:13.158000 (notice the three zeros at the end.)

How can I achieve this? (keep in mind, I'm not trying to format strings or anything. I want to format a date object.)

I guess one way would be to format it into a string with desired precision, like this:

dateString = date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

and then back to a date object. But there's got to be a better way.

Upvotes: 2

Views: 847

Answers (1)

Mark Ransom
Mark Ransom

Reputation: 308111

dt = dt.replace(microsecond = (dt.microsecond // 1000) * 1000)

This will truncate the last 3 digits. Proper rounding is a little more complicated due to the possibility that it might round to 1000000 microseconds.

Upvotes: 5

Related Questions