0

With the time value being:

value = '2017-08-31T02:24:29.000Z'

I try to convert it to a datetime object with:

import datetime 
datetime_object = datetime.datetime.strptime(value, '%Y-%b-%d  %I:%M%p')

But the command crashes with the exception:

ValueError: time data '2017-08-31T02:24:29.000Z' does not match format '%Y-%b-%d  %I:%M%p'
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
  • The error message says the time value is `Jun 1 2005 1:33PM`, but the question says it's `2017-08-31T02:24:29.000Z`. Which is it? – John Gordon Sep 02 '17 at 00:08
  • Good eye! Fixed. Thanks! – alphanumeric Sep 02 '17 at 00:09
  • Maybe your answer can be found [here](https://stackoverflow.com/questions/466345/converting-string-into-datetime). – Abe Sep 02 '17 at 00:11
  • 1
    The error message is exactly correct; the format string does not match the date value you're trying to convert. For example, the format string contains `%b`, which is supposed to be an abbreviated month name such as `Aug`. But your time value string uses a number for the month, not a name. – John Gordon Sep 02 '17 at 00:14
  • Aren't you missing the T and a colon plus some of other things? – OneCricketeer Sep 02 '17 at 00:21

2 Answers2

2

You should be using a builtin Python's datautil module instead of date time:

import dateutil.parser
value = '2017-08-31T02:24:29.000Z'
result = dateutil.parser.parse(value)
alphanumeric
  • 17,967
  • 64
  • 244
  • 392
1

First of all, you are missing the formatter for the microsecond.

Second of all, there is no second colon for dividing the minute and second.

Third, the %b operator is for the monthname (Jan,Feb,etc.). You want to use %m.

Final format is '%Y-%m-%dT%I:%M:%S.%fZ'.

This is your code:

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

You should get 2017-08-31 02:24:29 as the value of datetime_object.

Pokestar Fan
  • 174
  • 1
  • 12