سؤال

I have a timestamp string from a web log that looks like this:

10/Jun/2005:05:59:05 -0500

It like to convert it to a UNIX timestamp.

A datetime can be converted with time.mktime(datetime.timetuple())

According to the datetime docs, datetime.strptime() should convert it to a datetime:

from datetime import datetime
datetime.strptime("10/Jun/2005:05:59:05 -0500","%d/%b/%Y:%H:%M:%S %z")

At least on with Python 2.7.2 on my Mac, this results in

ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S %z'

After reading many questions on SO about that error, I decided to try python-dateutil:

from dateutil import parser
parser.parse("10/Jun/2005:05:59:05 -0500")

That didn't work either:

ValueError: unknown string format

Now what?

هل كانت مفيدة؟

المحلول

You can use dateutils to make the converstion, you will need two steps:

>>> import calendar
>>> from dateutil.parser import parse
>>> d = parse('10/Jun/2005:05:59:05 -0500', fuzzy=True)

This will create a datetime object

>>> d
datetime.datetime(2005, 6, 10, 5, 59, 5, tzinfo=tzoffset(None, -18000))

And to convert it to UNIX timestamp:

>>> ts = calendar.timegm(d.utctimetuple())
>>> print ts
1118401145
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top