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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-31 01:10:28

问题


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:

Convert this timestamp from an apache log (in CEST timezone):

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. Please do not propose solutions for python3


回答1:


Two steps:

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

    You've already done it. See How to parse dates with -0400 timezone string in python? on how to do it using only 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. 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. See Converting datetime.date to UTC timestamp in Python

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


来源:https://stackoverflow.com/questions/32371047/python2-6-6-convert-apache-log-timestamp-to-seconds-since-epoch-unix-style

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!