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]

(UTC オフセット) (少なくとも py2.x では) をdatetime.striptimeサポートしていないため、回避策が必要です。%z

#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 に答える