简体   繁体   English

python2.6.6将apache日志时间戳转换为epoch以来的秒数(unix样式)

[英]python2.6.6 Convert apache log timestamp to seconds since epoch (unix style)

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: 因为我在stackoverflow上找到的几十种方法完全丢失了时间戳转换,所以我在这里问完整的问题:

Convert this timestamp from an apache log (in CEST timezone): 从apache日志转换此时间戳(在CEST时区中):

30/Aug/2015:05:13:53 +0200

Into this: 进入:

1440904433

Using 运用

$ python --version
Python 2.6.6

Verification: 验证:

$ date --date @1440904433
Sun Aug 30 05:13:53 CEST 2015
$ date -u --date @1440904433
Sun Aug 30 03:13:53 UTC 2015

Bad results are: 不好的结果是:

1440911633
1440908033

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))

Please do not propose pytz module, I don't have it and I can't install it. 请不要提出pytz模块,我没有它,我无法安装它。 Please do not propose solutions for python3 请不要为python3提出解决方案

Two steps: 两个步骤:

  1. Convert the time string into an aware datetime object (or a naive datetime object that represents time in UTC). 将时间字符串转换为有意识的日期时间对象 (或表示UTC时间的天真datetime时间对象)。

     >>> 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)) 

    You've already done it. 你已经完成了。 See How to parse dates with -0400 timezone string in python? 请参阅如何在python中使用-0400时区字符串解析日期? on how to do it using only stdlib. 关于如何仅使用stdlib来做到这一点。

  2. 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 

    Use / and enable from __future__ import division , to get fractions of a second. 使用/from __future__ import division启用,以获得一秒的分数。 If you don't need to support fractions; 如果你不需要支持分数; you could simplify the formula: 你可以简化公式:

     >>> td.seconds + td.days * 86400 1440904433 

    If you get a utc time on the 1st step using only stdlib then you don't need dateutil.tz here. 如果你只使用stdlib在第一步获得了utc时间,那么你在这里不需要dateutil.tz See Converting datetime.date to UTC timestamp in Python 请参阅在Python中将datetime.date转换为UTC时间戳

Here's a Python 3 solution for visitors from a search engine: 这是针对来自搜索引擎的访问者的Python 3解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM