Skip to content

Date strings with inconsistent spaces

wordpress meta

title: 'Date strings with inconsistent spaces'
date: '2017-01-23T10:51:54-06:00'
status: publish
permalink: /date-strings-with-inconsistent-spaces
author: admin
excerpt: ''
type: post
id: 1038
category:
    - Python
tag: []
post_format: []

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'
  d=''.join(new)

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'))