0

I'm trying to convert a datetime string to a datetime object. The datetime string looks like this:

2020-05-04 2004:33:39.654942

I tried using datetime.datetime.strptime method by implementing:

datetime.datetime.strptime("2020-05-04 2004:33:39.654942","%Y-%m-%d %H%M:%S:%f")

I however got the following error:

ValueError: unconverted data remains: .654942

I tried using %Y-%m-%d %H%M:%S:%f%Z, %Y-%m-%d %H%M:%S:%f.%Z and %Y-%m-%d %H%M:%S:%f%z, %Y-%m-%d %H%M:%S:%f.%z, however I am still not getting the correct format. Anyone have any suggestions what I can do?

sandrosil
  • 543
  • 3
  • 9
  • 21
  • 1
    It looks like `hour = 20, minute = 04, second = 33`. How should we interpret the 39.654942 part? Specifically, how many microseconds does this represent? – Kota Mori May 05 '20 at 13:46
  • @KotaMori for `strptime`, would there be any possibility to parse `39.654942` as microseconds? I can't think of any... – FObersteiner May 05 '20 at 13:51
  • @MrFuppes, like what @KotaMori said, the format of my string is ```hour = 20```, ```minute = 04```, ```seconds=33```. What is the ```39.654942``` based on my research the ```39``` is microseconds and ```0.654942``` is milliseconds? – sandrosil May 05 '20 at 13:55
  • @MrFuppes I believe not. According to the docs, https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes, microseconds part should be six digits. – Kota Mori May 05 '20 at 13:58
  • 2
    If we assume that the string input has no error, one possible interpretation would be 39 is microseconds and .654942 represents nanoseconds. If so, python's datetime object does not support it (it supports only up to microseconds): https://stackoverflow.com/questions/10611328/parsing-datetime-strings-containing-nanoseconds. That said, I would double-check that the string input is correct since this format is something rarely seen. – Kota Mori May 05 '20 at 14:02
  • if you need to work with a higher precision than microseconds, have a look at the datetime64 data type from `numpy` (also in `pandas`). – FObersteiner May 05 '20 at 14:10
  • Ok, i think for now I might just strip it until microseconds. Thank you @MrFuppes – sandrosil May 05 '20 at 14:15

0 Answers0