0

I've tried several perturbations of the following:

datetime.strptime('2018-01-14T23:55:27.337Z',"%Y-%m-%dT%H:%M:%S.%3N%Z")

but get errors like this:

ValueError Traceback (most recent call last)
<ipython-input-45-babd38d0d73f> in <module>()----> 1 datetime.strptime('2018-01-14T23:55:27.337Z',"%Y-%m-%dT%H:%M:%S.%3N%Z")
/usr/lib/python3.5/_strptime.py in _strptime_datetime(cls, data_string, format)
    508     """Return a class cls instance based on the input string and the
    509     format string."""
--> 510     tt, fraction = _strptime(data_string, format)
    511     tzname, gmtoff = tt[-2:]
    512     args = tt[:6] + (fraction,)

/usr/lib/python3.5/_strptime.py in _strptime(data_string, format)
    333                 del err
    334                 raise ValueError("'%s' is a bad directive in format '%s'" %
--> 335                                     (bad_directive, format)) from None
    336             # IndexError only occurs when the format string is "%"
    337             except IndexError:

ValueError: '3' is a bad directive in format '%Y-%m-%dT%H:%M:%S.%3N%Z'
user3591836
  • 953
  • 2
  • 16
  • 29

1 Answers1

0

Try doing this.

datetime.strptime('2018-01-14T23:55:27.337Z', '%Y-%m-%dT%H:%M:%S.%fZ')

Take note at the second argument. It's '%Y-%m-%dT%H:%M:%S.%fZ' and not '%Y-%m-%dT%H:%M:%S.%3N%Z'. You are getting a bad directive value error because %3 is not a directive.

In case you need it, here's the documentation for strptime().

Sean Francis N. Ballais
  • 2,338
  • 2
  • 24
  • 42
  • Yes this works but how do you keep it at 3 significant figures in the milliseconds after doing datetime manipulation? Eg. when i add timedelta of 1 day it then defaults to .000000Z – user3591836 Jan 16 '18 at 06:46
  • You can't do that by setting it in the directives. What you could do is remove the trailing digits in string input first (e.g. `'2018-01-14T23:55:27.337Z'`) then pass it to `strptime()`. – Sean Francis N. Ballais Jan 16 '18 at 06:51
  • @user3591836 By 3 significant figures, you mean round the remaining milliseconds up to the 3rd significant figure or just keep three digits in the milliseconds part? – Sean Francis N. Ballais Jan 16 '18 at 07:06
  • Either would be fine for this application. – user3591836 Jan 17 '18 at 08:11
  • Well, okay. If you want to round the milliseconds off to the 3rd significant figure, get the milliseconds part of the seconds part first (e.g. get `337` from `27.337Z`) then convert it to a decimal (e.g. from `337` to `0.337`). Then round that decimal off to the 3rd significant figure. [Here's](https://stackoverflow.com/questions/3410976/how-to-round-a-number-to-significant-figures-in-python) a QA on rounding off to significant figures. The result you get replaces the milliseconds part from the input string you have. – Sean Francis N. Ballais Jan 17 '18 at 08:22