117

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
  • 4,191
  • 4
  • 40
  • 54

1 Answers1

265

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
  • 88,551
  • 18
  • 188
  • 176
  • 5
    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
  • 3
    It may be old, but I'm about to pass 100 upvotes! So perhaps the source documentation remains too vague, 7 years later? – Marc Maxmeister Jul 11 '22 at 19:26
  • 2
    yep 2023 still works – greendino Mar 16 '23 at 10:22