96

My colleague needs me to drop the milliseconds from my python timestamp objects in order to comply with the old POSIX (IEEE Std 1003.1-1988) standard. The tortured route that accomplishes this task for me is as follows:

datetime.datetime.strptime(datetime.datetime.today().strftime("%Y-%m-%d %H:%M:%S"),"%Y-%m-%d %H:%M:%S")

Is there a simpler way to end up with a datetime.datetime object for mongoDB than this?

Marc Maxmeister
  • 3,607
  • 2
  • 33
  • 47

1 Answers1

213

You can use datetime.replace() method -

>>> d = datetime.datetime.today().replace(microsecond=0)
>>> d
datetime.datetime(2015, 7, 18, 9, 50, 20)
Anand S Kumar
  • 82,977
  • 18
  • 174
  • 164
  • This question is old, but I would like to add that you would need to do something like this if you intend to keep milliseconds `now = datetime.utcnow()` `now.replace(microsecond=round(now.microsecond, -3))` – Curt Mar 19 '22 at 16:34