2

PHP has the amazing strtotime() function which takes pretty much anything and turns it into a time.

I'm looking for something similar in Python?

As an example of why: I'm parsing syslogs which have the dumbest format ever (aka rfc3164) which omits a year and includes a space-padded day-of-month.

Currently in Python I'm doing this:

import datetime
d='Mar  5 09:10:11' # as an example

# first remove the space, if it exists
if d[4] == ' ':
   d = d[0:4] + d[5:]
# append this year (I know, it could be last year around Dec/Jan!)
d =  str(datetime.datetime.now().year) + ' ' + d

# now we can feed it strptime
date = datetime.strptime(d, "%Y %b %d %H:%M:%S")

This is really ugly.

Is there a better way?

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
artfulrobot
  • 20,637
  • 11
  • 55
  • 81

1 Answers1

1

I think you are looking for the dateutils module:

In [12]: d = 'Mar  5 09:10:11'

In [13]: import dateutil

In [14]: dateutil.parser.parse(d)
Out[14]: datetime.datetime(2015, 3, 5, 9, 10, 11)
Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
  • Surprising Python doesn't have this in core. But thanks, that's exactly what I needed. – artfulrobot Mar 05 '15 at 13:27
  • Yes, thanks, it's the dumb "oh you can't accept this answer for 36.4 seconds" thing that made me forget. Must ask on meta what the purpose of those limitations is one day! – artfulrobot Mar 26 '15 at 16:33