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?
views:
4895answers:
5
+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
2008-10-18 09:01:59
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
2008-10-18 09:04:31
Unfortunately, the strptime function doesn't seem to have a conversion operator for milliseconds.
Greg Hewgill
2008-10-18 09:05:05
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
2008-10-18 09:07:03
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
2008-10-19 03:13:24
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
2008-10-19 03:30:06
+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
2008-10-18 14:13:19
+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
2008-10-18 17:33:30
A:
wat ever Greg Hewgill says absolutely works.. so there is no need of a better answer
Meenakshi
2010-03-29 11:40:53
@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).
ΤΖΩΤΖΙΟΥ
2010-03-31 23:11:47
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
2010-05-25 12:32:41