4

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.

4

1 回答 1

6

由于 py2.x%z指令存在问题,您必须执行以下操作:

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]

由于datetime.striptime不支持%z(UTC 偏移)(至少在 py2.x 中不支持),因此您需要解决方法:

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

delta = timedelta(hours = offset / 100)

现在将格式应用于: '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
于 2013-07-05T18:04:44.327 回答