Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert custom strings to datetime format

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!

like image 210
Litwos Avatar asked Sep 06 '25 18:09

Litwos


1 Answers

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'
like image 132
fredtantini Avatar answered Sep 11 '25 10:09

fredtantini