Python datetime to string without microsecond component

If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:

>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

See the documentation of datetime.strftime() for an explanation of the % directives.

Starting from Python 3.6, the isoformat() method is flexible enough to also produce this format:

datetime.datetime.now().isoformat(sep=" ", timespec="seconds")

>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07