0

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?

MeatBALL
  • 65
  • 1
  • 8
  • 2
    Does this answer your question? [Parsing datetime strings containing nanoseconds](https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds) – buran Feb 16 '22 at 12:45
  • @buran I decided to slice the last three digits as one of the answers suggested. It seems that I anyway would need to slice them out – MeatBALL Feb 16 '22 at 12:49
  • 1
    That's always a possible approach. – buran Feb 16 '22 at 12:50
  • [pandas datetime](https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html) allows you to keep the nanoseconds, as it uses nanosecond precision. – FObersteiner Feb 16 '22 at 15:58

2 Answers2

1

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)
TheFaultInOurStars
  • 3,464
  • 1
  • 8
  • 29
0

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

MeatBALL
  • 65
  • 1
  • 8