Home > database >  Python datetime specify amount of milliseconds after the decimal point
Python datetime specify amount of milliseconds after the decimal point

Time:02-17

I have a string of time that looks like this: "2022-02-16T14:33:25.943971072". I tried to convert it to a datetime object with this format '%Y-%m-%dT%H:%M:%S.%f', but it doesn't work because it expects to get 6 digits of milliseconds.

What should be the format to convert the string to datetime?

CodePudding user response:

If you want to pass inputting the format and change the string to a datetime object without knowing the format, you can simply use dateutil and parser:

from dateutil import parser
parser.parse("2022-02-16T14:33:25.943971072")

Output

datetime.datetime(2022, 2, 16, 14, 33, 25, 943971)

CodePudding user response:

If I'm not wrong datetime doesn't support in more than 6 digits in the millisecond part. I liked the suggestion of @Amirhossein Kiani above, I believe a simpler solution is just slicing the string:

datetime.datetime.strptime"2022-02-16T14:33:25.943971072")[:-3], '%Y-%m-%dT%H:%M:%S.%f')

There maybe a more elegant wat to slice it but it works

  • Related