5

I have a log file with timestamps like "2012-05-12T13:04:35.347-07:00". I want to convert each timestamp into a number so that I sort them by ascending order based on time.

How can I do this in Python? In Java I found out that I can convert timestamps for such format with SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") but for Python I couldn't find anything.

user1048858
  • 393
  • 3
  • 5
  • 14
  • 1
    `012`? YYY is an actual time format? Please tell me that was a copy+paste error. – yurisich Jul 05 '13 at 17:40
  • That is almost the format specified in ISO8601 (guessing you made some minor transcription errors) and sorting them alphabetically equals sorting the chronologically, so maybe you don't have to convert at all... – fvu Jul 05 '13 at 17:40
  • oh yes, sorry. i missed a "2" in the beginning, it should be "2012-05-12T13:04:35.347-07:00". So if I just sort them as strings, I will get the same order vs. converting into time format? – user1048858 Jul 05 '13 at 17:50
  • @AshwiniChaudhary I am coding in Python 2.7.2. – user1048858 Jul 05 '13 at 17:59

1 Answers1

6

As py2.x has issues with the %z directive you've to do something like this:

from datetime import timedelta,datetime
strs = "2012-05-12T13:04:35.347-07:00"
#replace the last ':' with an empty string, as python UTC offset format is +HHMM
strs = strs[::-1].replace(':','',1)[::-1]

As datetime.striptime doesn't supports %z(UTC offset)(at least not in py2.x), so you need a work around:

#Snippet taken from http://stackoverflow.com/a/526450/846892
try:
    offset = int(strs[-5:])
except:
    print "Error"

delta = timedelta(hours = offset / 100)

Now apply formatting to : '2012-05-12T13:04:35.347'

time = datetime.strptime(strs[:-5], "%Y-%m-%dT%H:%M:%S.%f")
time -= delta                #reduce the delta from this time object
print time
#2012-05-12 20:04:35.347000
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504