Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python datetime utcnow() milliseconds to 9 digits?

I am attempting to format a datetime string to have the milliseconds represented as 9 digits. I cannot figure out how to do this without manipulating the whole string. I currently have

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

and I would like the milliseconds (%f) printed as 9 digits, instead of the default 6. How do I do this?

Just to clarify, I don't need 9 digit precision, I just need to print, for example, 2013-07-19 09:28:00.000544913 with the three padded 0's.


2 Answers

datetime.datetime.utcnow().strftime('%Y-%m%d %H:%M:%S.000%f')

Seems to work for me.

Physically you should do this to get the correct representation of the time:

datetime.datetime.utcnow().strftime('%Y-%m%d %H:%M:%S.%f000')
like image 135
skyline75489 Avatar answered Dec 02 '25 01:12

skyline75489


First, milliseconds to 9 digits wouldn't make any sense. The "milli" means "thousandths", as in 3 digits.

Second, you don't have milliseconds, you have microseconds. The datetime type has a microseconds attribute, and %f is defined as microseconds. And of course "micro" means "millionths", as in 6 digits.

Since there are no nanoseconds being stored in the object, it wouldn't make much sense to have a nanoseconds format specifier. But, if there were a nanoseconds format specifier, it would just be the microseconds with an extra three 0's at the end, which you can just do yourself:

'%Y-%m%d %H:%M:%S.%f000'

Alternatively, nobody's forcing you to use strfime; you could always use str.format and include a {:09} field and pass dt.microseconds * 1000 to it.

like image 31
abarnert Avatar answered Dec 02 '25 01:12

abarnert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!