0

When calling an API, I am getting seven digits in the decimal part of the seconds in datetime string. Below is the value that I got in response:

"startDateTime": "2020-09-16T10:02:38.5904496Z"

Clearly 5904496 are seven digits. If there would have been 6 digits then I would have used the below code to convert this into datetime object:

from datetime import datetime

datetime_object = datetime.strptime(startDateTime, '%Y-%m-%dT%H:%M:%S.%fZ')

But I get this error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/lib/python3.6/_strptime.py", line 565, in _strptime_datetime
    tt, fraction = _strptime(data_string, format)
  File "/usr/lib/python3.6/_strptime.py", line 362, in _strptime
    (data_string, format))
ValueError: time data '2020-09-16T10:02:38.5904496Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

How do I handle 7 digits in decimal part of seconds?

P.S: I know I can use python dateutil library but I should know how to do this. I will really be thankful if you can shed some light on this.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Amandeep Singh
  • 1,371
  • 1
  • 11
  • 33
  • 2
    do you need the 7 digit accuracy? – Bendik Knapstad Sep 16 '20 at 13:12
  • @BendikKnapstad I am being honest. I knew that i could strip the seventh digit but i thought there may be a directive for ```10^(-7)``` just like we have %f for microseconds. So for my knowledge i asked this question. Thanks for the reference though. – Amandeep Singh Sep 17 '20 at 06:56

2 Answers2

3

If you don't need the precision, just chop it off.

d = "2020-09-16T10:02:38.5904496Z"
datetime.datetime.strptime(d.split(".")[0], "%Y-%m-%dT%H:%M:%S")

Output: datetime.datetime(2020, 9, 16, 10, 2, 38)

If you want to keep it thou.

>>> datetime.datetime.strptime(d[:-2], "%Y-%m-%dT%H:%M:%S.%f")
>>> datetime.datetime(2020, 9, 16, 10, 2, 38, 590449)
baduker
  • 19,152
  • 9
  • 33
  • 56
  • Precision is not an issue. I am being honest. I knew that i could strip the seventh digit but i thought there may be a directive for ```10^(-7)``` just like we have %f for microseconds. So for my knowledge i asked this question. Thanks for the answer though. – Amandeep Singh Sep 17 '20 at 06:58
  • that ignores the fact that the input is UTC ('Z') - a thing to consider carefully when using Python since it does not default to UTC with its naive datetime type. – FObersteiner Feb 03 '23 at 04:13
1

for completeness, numpy's datetime64 handles fractional seconds with nanosecond resolution:

import numpy as np
arr = np.array(["2020-09-16T10:02:38.5904496Z"], dtype=np.datetime64)
print(arr[0])
>>> 2020-09-16T10:02:38.590449600

However, here it fails to parse Z to UTC. This works fine with pandas, as I show in the linked question's answer.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
  • Since this is the accepted answer, I cannot delete it. Please follow the duplicate link for a more comprehensive answer. – FObersteiner Feb 03 '23 at 04:17