问题
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:
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.
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 enablefrom __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