Ways to get number of seconds from Epoch
Fredrik Lundh
fredrik at pythonware.com
Wed May 1 16:46:25 EDT 2002
Václav Sigmund wrote:> I am a Python newbie and I sudenly run into following problem:
>
> I would like to write a tool to analyze the access.log records from my
> company's webserver, and it would be very convenient for to convert dates
> date of the record into number of seconds from Epoch (let's call it
> "standard unix time" for convenience).
>
> Each record have recorded time as follows:
>
> [15/Apr/2002:08:28:56 +0200]
is that gmt+zone or localtime-zone? cannot remember.
but here's a reasonable start:
import re, calendar, time
text = "[15/Apr/2002:08:28:56 +0200]"
MONTHS = [
None,
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]
p = re.compile("\[(\d+)/(\w+)/(\d+):(\d+):(\d+):(\d+) ([-+]\d+)\]")
m = p.match(text)
# extract date/time fields
year, day = map(int, m.group(3, 1))
month = calendar.month_abbr.index(m.group(2))
hour, minute, second = map(int, m.group(4, 5, 6))
offset = int(m.group(7))
unixtime = calendar.timegm((year, month, day, hour, minute, second))
print time.gmtime(unixtime)
# prints (2002, 4, 15, 8, 28, 56, 0, 105, 0)
</F>
<!-- (the eff-bot guide to) the python standard library:
http://www.pythonware.com/people/fredrik/librarybook.htm
-->
More information about the Python-list
mailing list