Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple way to drop milliseconds from python datetime.datetime object [duplicate]

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?

like image 573
Marc Maxmeister Avatar asked Jul 18 '15 04:07

Marc Maxmeister


People also ask

How do I remove milliseconds from a timestamp?

Use the setSeconds() method to remove the seconds and milliseconds from a date, e.g. date. setSeconds(0, 0) . The setSeconds method takes the seconds and milliseconds as parameters and sets the provided values on the date.

How do I remove seconds from a datetime object in Python?

If you just want strings, you could remove the trailing seconds with a regex ':\d\d$' .

How do I get rid of microseconds Python?

This method takes a datetime object and returns a character string representing the date in ISO 8601 format. To get rid of the microseconds component, we have to specify the keyword 'seconds' within the isoformat function.


1 Answers

You can use datetime.replace() method -

>>> d = datetime.datetime.today().replace(microsecond=0) >>> d datetime.datetime(2015, 7, 18, 9, 50, 20) 
like image 154
Anand S Kumar Avatar answered Sep 18 '22 12:09

Anand S Kumar