3

I have a list of date-time data strings that looks like this:

list = ["2016-08-02T09:20:32.456Z", "2016-07-03T09:22:35.129Z"]

I want to convert this to the example format (for the first item):

"8/2/2016 9:20:32 AM"

I tried this:

from datetime import datetime
for time in list:
    date = datetime.strptime(time, '%Y %m %d %I %R')

But returns error:

ValueError: 'R' is a bad directive in format '%Y %m %d %I %R'

Thanks for any help!

Litwos
  • 1,278
  • 4
  • 19
  • 44
  • The date format that you are using does not match the items of your list. And what is `%R` supposed to mean? – S. de Melo Oct 14 '16 at 10:56
  • It's supposed to mean the time in 24hour duration: https://www.tutorialspoint.com/python/time_strptime.htm – Litwos Oct 14 '16 at 11:00
  • Strange, it does not appear in the official documentation: https://docs.python.org/3.0/library/datetime.html#id1 – S. de Melo Oct 14 '16 at 11:03

2 Answers2

3

You have several problems in you code:

  • %Rdoesn't seem to be a correct directive (that's your error, I think you are looking for %p).
  • the format in strptime is the format of your input, not the output
  • you are using list and time as a name variable which is bad ;]

So, you could for first convert you time to a correct datetime object:

>>> t='2016-08-02T09:20:32.456Z'
>>> d=datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%fZ")
>>> d
datetime.datetime(2016, 8, 2, 9, 20, 32, 456000)

And then convert this object to a string with strftime

>>> datetime.strftime(d, "%m/%d/%Y %I:%M:%S %p")
'08/02/2016 09:20:32 AM'
fredtantini
  • 15,966
  • 8
  • 49
  • 55
1
s = "2016-08-02T09:20:32.456Z"
d = datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ")

The use d.strftime (https://docs.python.org/3.0/library/datetime.html#id1).

S. de Melo
  • 786
  • 4
  • 11