I have a log with following date format:

2013-12-14 18:53:33 aaaaaaaaaaaaaaaa
2013-12-14 18:53:33 bbbbbbbbb
2013-12-14 18:53:33 ccccccccccccccccccccc

What would be the simplest solution to convert it to

Dec 14 18:53:33 aaaaaaaaaaaaaaaa
Dec 14 18:53:33 bbbbbbbbb
Dec 14 18:53:33 ccccccccccccccccccccc

preferably in bash (or python)

4 Answers 4


You could do something like:

awk -F- 'BEGIN{split("Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",m,",")}
         {print m[$2], substr($0,9)}'


awk -F- '{print substr("JanFebMarAprMayJunJulAugSepOctNovDec", \
         $2*3-2,3), substr($0,9)}'


sed 's/$/:01Jan02Feb03Mar04Apr05May06Jun07Jul08Aug09Sep10Oct11Nov12Dec/
     s/.....\(..\).\(.*\):.*\1\(...\).*/\3 \2/'

In bash, you could do the following:

$ tmpdate='2013-09-16 16:06:18,145-0500'
$ date +%c -d "$tmpdate"
Mon 16 Sep 2013 05:06:18 PM EDT

So, in the log line that you have, you could extract the date field as follows:

tmpdate=`echo "2013-12-14 18:53:33 aaaaaaaaaaaaaaaa" | cut -f1-2 -d ' '`

For more date formats, see: http://www.gnu.org/software/coreutils/manual/html_node/Date-input-formats.html#Date-input-formats


Use python convert.py < logfile with convert.py:

import sys
from datetime import datetime

for line in sys.stdin:
    dts = line[:19]
    d = datetime.strptime(dts, '%Y-%m-%d %H:%M:%S')
    print d.strftime("%b %d %H:%M:%S"), line[20:],

This can be further optimized as the hours, minutes, seconds don't have to be parsed. %b in strftime prints the month name according to your locale.


Python (input file - data.log, output file - out.log)

#!/usr/bin/env python
import datetime
import os
with open('data.log') as f, open('out.log', 'w') as f2:
  for line in f:
    log_date, text = line.rsplit(None, 1)
    log_date = datetime.datetime.strptime(log_date, '%Y-%m-%d %H:%M:%S')
    log_date = log_date.strftime('%b %d %H:%M:%S')
    f2.write('{} {}{}'.format(log_date, text, os.linesep))

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .