4

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!

3

2 Answers 2

4

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'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the better answer and explanations!
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.