2

I have a datetime string "2017-02-14T18:21:14.080+05:30". The code I used is

from dateutil.parser import parse
print parse("2017-02-14T18:21:14.080+05:30")

The datetime.datetime object I get is

2017-02-14 18:21:14.080000+05:30

Is there anyway python allows me to set the precision of the milliseconds value displayed before timezone info to 3 in order to get the output as

2017-02-14 18:21:14.080+05:30
Wolfie
  • 27,562
  • 7
  • 28
  • 55
Avinash Kumar
  • 25
  • 1
  • 5

1 Answers1

2

There is no built-in way to ask Python to display dates with milliseconds. You'll have to do a bit of string manipulation to get the desired result:

from dateutil.parser import parse
import datetime as DT
date = parse("2017-02-14T18:21:14.080+05:30")
microsecond = date.microsecond
millisecond = int(round(microsecond/1000))
print(str(date).replace('.{:06d}'.format(microsecond), 
                        '.{:03d}'.format(millisecond)))

yields

2017-02-14 18:21:14.080+05:30

See this post for solutions and discussion of how to convert microseconds to milliseconds. Note that one of the difficulties is that date.microsecond may return a number with fewer than 6 digits, and if microseconds are 0, on some OSes, str(date) may drop the microseconds altogether). This is why some pains were taken above to format microseconds to 6 digits before replacing with milliseconds formatted to 3 digits.

Using the code above, on an OS which drops microseconds when zero, no milliseconds would be shown. If you wish to always show milliseconds formatted to 3 decimal places, you'll have to build the date string from scratch:

from dateutil.parser import parse
import datetime as DT
date = parse("2017-02-14T18:21:14.080+05:30")
microsecond = date.microsecond
millisecond = round(microsecond/1000)
utcoffset = date.strftime('%z')
utcoffset_string = '{}:{}'.format(utcoffset[:-2], utcoffset[-2:])
print('{}{}{}'.format(date.strftime('%Y-%m-%dT%H:%M:%S'), 
                      '.{:03d}'.format(millisecond),
                      utcoffset_string))
Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Thank you, your solution suits my need. A friend of mine suggested string manipulation, but I wanted to know whether there existed some function to do this. Im new to python and searched a lot but couldn't quite get this done. – Avinash Kumar Apr 15 '17 at 08:33
  • Solution 1 gave me an error that said ValueError: Unknown format code 'd' for object of type 'float'. Tried replacing d with f, but returned the same string. Ended up force converting everything into int and your code worked. Leaving the code that worked here, below. Thanks again. microsecond = int(dt.microsecond) millisecond = int(round(microsecond/1000)) print(str(dt).replace('.{:06d}'.format(microsecond), '.{:03d}'.format(millisecond))) – Avinash Kumar Apr 15 '17 at 09:58