Anoop M Nair
Anoop M Nair

Reputation: 1087

How to get time value in milliseconds from a date object python?

As part of my new work I need to convert one existing java class to a python one.

person.setDob(String.valueOf(person.getDateOfBirth().getTime()));

Please see the above snippet here how to fetch time in milliseconds from date object in python, Hope I can use datetime.datetime for this purpose. Please help.

Upvotes: 0

Views: 467

Answers (2)

Anjali
Anjali

Reputation: 1718

To get milliseconds in python, use the below code.

 import datetime
 print('Datetime in milliscond using now()',datetime.datetime.now())
 print('Datetime in milliscond using utcfromtimestamp()', datetime.datetime.utcfromtimestamp(0))

output looks like below

 Datetime in milliscond using now() 2019-03-11 17:34:28.290409
 Datetime in milliscond using now() 1970-01-01 00:00:00

Upvotes: 0

Cipher
Cipher

Reputation: 2122

To get a date string with milliseconds (3 decimal places behind seconds), use this:

from datetime import datetime

print datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

OUTPUT 2018-10-04 10:18:32.926

%f is displaying milliseconds

Upvotes: 1

Related Questions