Python datetime to string without microsecond component

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).

What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?

>>> import datetime
>>> print unicode(
2011-11-03 11:13:39.278026

I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.

Edit: I should mention that I'm not actually printing the current time – I used to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.

Read more here:

Content Attribution

This content was originally published by davidchambers at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: