views:

4895

answers:

5

For example, I'm trying to convert 2008-09-26T01:51:42.000Z to 09/26/2008. What's the simplest way of accomplishing this?

+10  A: 
>>> import time
>>> timestamp = "2008-09-26T01:51:42.000Z"
>>> ts = time.strptime(timestamp[:19], "%Y-%m-%dT%H:%M:%S")
>>> time.strftime("%m/%d/%Y", ts)
'09/26/2008'

See the documentation of the Python time module for more information.

Greg Hewgill
I know that in this case they are not relevant, of course, but is there a way to handle milliseconds short of stripping them?
Vinko Vrsalovic
Unfortunately, the strptime function doesn't seem to have a conversion operator for milliseconds.
Greg Hewgill
Although the answer seems quite complete, if you want to read more on the python/date-time subject I'd suggest this page http://pleac.sourceforge.net/pleac_python/datesandtimes.html
Seldaek
While this solution does get the desired result, it does not take into account the timezone (in this case UTC). This could be undesirable in some cases.
Jeremy Cantrell
Jeremy: the OP didn't ask anything about local time conversion. The solution above manipulates the components of the timestamp without regard to time zone.
Greg Hewgill
+1  A: 

2008-09-26T01:51:42.000Z is an ISO8601 date and the format can be very diverse. If you want to parse these dates see the python wiki on working with time. It contains some useful links to modules.

olt
+10  A: 

The easiest way is to use dateutil.parser.parse() to parse the date string into a timezone aware datetime object, then use strftime() to get the format you want.

import datetime, dateutil.parser

d = dateutil.parser.parse('2008-09-26T01:51:42.000Z')
print d.strftime('%m/%d/%Y') #==> '09/26/2008'
Jeremy Cantrell
A: 

wat ever Greg Hewgill says absolutely works.. so there is no need of a better answer

Meenakshi
@Meenakshi: I didn't downvote you, but you really should delete this “answer” (hint: it's not an answer; at best, it should be a comment to Greg's answer).
ΤΖΩΤΖΙΟΥ
A: 
def datechange(datestr):
dateobj=datestr.split('-')
y=dateobj[0]
m=dateobj[1]
d=dateobj[2]
datestr=d +'-'+ m +'-'+y
return datestr

U can make a function like this which take date object andd returns you date in desired dateFormat....

Dhaval dave