Riaan's SysAdmin Blog

My tips, howtos, gotchas, snippets and stuff. Use at your own risk!


Date strings with inconsistent spaces

I frequently bump into manipulating very large log files and the date input strings are formatted poorly.

Couple problems for me here:
1. Input is like this "Sat Feb 6 03:25:01 2016". You can see there is a double space in front of 6. a "06" may have been more useful. The additional space gives python's strptime fits and I have to do something like this.
2. Sorting "Sat Feb ..." is not ideal so reformat it to something like "2016-02-06..." may work better down the line. Maybe in Excel or Calc.

import datetime

d = 'Sat Feb  6 03:25:01 2016'
#d = 'Sat Feb 19 03:25:01 2016'

if d[8:9] == ' ':
  new = list(d)
  new[8] = '0'

print "Useful date is: {dt}".format(dt=datetime.datetime.strptime(d,'%a %b %d %H:%M:%S %Y').strftime('%Y-%m-%d %H:%M:%S'))


Bio Info for Riaan