Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将时间戳转换为";yyyy-MM-dd';T';HH:mm:ss.SSSZ“;Python格式_Python_Timestamp - Fatal编程技术网

将时间戳转换为";yyyy-MM-dd';T';HH:mm:ss.SSSZ“;Python格式

将时间戳转换为";yyyy-MM-dd';T';HH:mm:ss.SSSZ“;Python格式,python,timestamp,Python,Timestamp,我有一个带有时间戳的日志文件,如“2012-05-12T13:04:35.347-07:00”。我想将每个时间戳转换成一个数字,以便根据时间按升序对它们进行排序 如何在Python中实现这一点?在Java中,我发现我可以使用SimpleDataFormat(“yyyy-MM-dd'HH:MM:ss.SSSZ”)为这种格式转换时间戳,但对于Python,我找不到任何东西。由于py2.x在%z指令中存在问题,您必须执行以下操作: from datetime import timedelta,date

我有一个带有时间戳的日志文件,如“2012-05-12T13:04:35.347-07:00”。我想将每个时间戳转换成一个数字,以便根据时间按升序对它们进行排序


如何在Python中实现这一点?在Java中,我发现我可以使用SimpleDataFormat(“yyyy-MM-dd'HH:MM:ss.SSSZ”)为这种格式转换时间戳,但对于Python,我找不到任何东西。

由于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

012
?YYY是实际时间格式吗?请告诉我这是一个复制+粘贴错误。这几乎是ISO8601中指定的格式(猜测您犯了一些小的转录错误),按字母顺序排序等于按时间顺序排序,所以您可能根本不需要转换…哦,是的,对不起。一开始我漏掉了一个“2”,应该是“2012-05-12T13:04:35.347-07:00”。因此,如果我只是将它们作为字符串排序,我将得到与转换为时间格式相同的顺序?@AshwiniChaudhary我正在用Python 2.7.2编写代码。@user1048858请尝试我的解决方案。