python2.6.6转换Apache日志时间戳纪元以来的秒数(UNIX风格)
由于我完全失去了在几十你找计算器上做时间戳转换的方式,所以我会在这里问完整的问题:
As I am completely lost in the dozens of ways you find on stackoverflow to do timestamp conversions, so I will ask here the complete question:
从Apache日志转换时间戳(以CEST时区):
Convert this timestamp from an apache log (in CEST timezone):
30/Aug/2015:05:13:53 +0200
进入这个:
1440904433
使用
$ python --version
Python 2.6.6
验证:
$ date --date @1440904433
Sun Aug 30 05:13:53 CEST 2015
$ date -u --date @1440904433
Sun Aug 30 03:13:53 UTC 2015
坏的结果是:
1440911633
1440908033
我目前的code去,直到在这里:
My current code goes until here:
>>> from dateutil import parser
>>> parser.parse("30/Aug/2015:05:13:53 +0200".replace(':',' ',1))
datetime.datetime(2015, 8, 30, 5, 13, 53, tzinfo=tzoffset(None, 7200))
请不建议pytz模块,我没有它,我不能安装它。
请不要提出解决方案python3
Please do not propose pytz module, I don't have it and I can't install it. Please do not propose solutions for python3
两个步骤:
-
转换时间字符串转换为了解DateTime对象(或幼稚
日期时间
对象,在UTC重新presents时间)。
Convert the time string into an aware datetime object (or a naive
datetime
object that represents time in UTC).
>>> from dateutil import parser
>>> parser.parse("30/Aug/2015:05:13:53 +0200".replace(':', ' ', 1))
datetime.datetime(2015, 8, 30, 5, 13, 53, tzinfo=tzoffset(None, 7200))
您已经做到了。见如何与蟒蛇-0400时区字符串解析日期?的有关如何使用只STDLIB做到这一点。
You've already done it. See How to parse dates with -0400 timezone string in python? on how to do it using only stdlib.
转换一个知道DateTime对象,秒自大纪元
Convert an aware datetime object to "seconds since the Epoch":
>>> from datetime import datetime
>>> from dateutil import tz
>>> td = d - datetime(1970, 1, 1, tzinfo=tz.tzutc())
>>> td
datetime.timedelta(16677, 11633)
>>> (td.microseconds + (td.seconds + td.days * 86400) * 10**6) // 10**6
1440904433
使用 /
并从__future__进口部启用,获得第二的分数。如果不需要支持馏分;你可以简化公式:
Use /
and enable from __future__ import division
, to get fractions of a second. If you don't need to support fractions; you could simplify the formula:
>>> td.seconds + td.days * 86400
1440904433
如果你只使用stdlib,那么你不需要 dateutil.tz
在这里得到一个UTC时间上的第一步。请参见转换datetime.date在Python UTC时间戳
If you get a utc time on the 1st step using only stdlib then you don't need dateutil.tz
here. See Converting datetime.date to UTC timestamp in Python
下面是供游人Python 3的解决方案,从搜索引擎:
Here's a Python 3 solution for visitors from a search engine:
>>> from datetime import datetime
>>> d = datetime.strptime("30/Aug/2015:05:13:53 +0200", "%d/%b/%Y:%H:%M:%S %z")
>>> d.timestamp()
1440904433.0