4

I have the following code (based on http://strftime.org/):

try:
    datetime.datetime.strptime("Apr 14, 2016 9", '%b %d, %Y %-I')
    print "matched date format"
except ValueError:
    print "did NOT match date format"

The above prints:

$ python parse_log.py
did NOT match date format

However bash recognizes this date format:

$ date  '+%b %d, %Y %-I'
Apr 14, 2016 1

What am I missing?

It seems that the %-I is the problem, since Python matches date without the %-I section:

try:
    datetime.datetime.strptime("Apr 14, 2016 ", '%b %d, %Y ')
    print "matched date format"
except ValueError:
    print "did NOT match date format"

output:

$ python parse_log.py
matched date format

I'm on python 2.6.6.

The actual pattern I need to match uses 12 hour clock and is:

datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %-I:%M:%S')
Lidia
  • 2,005
  • 5
  • 25
  • 32

1 Answers1

5

You need to remove the - for strptime:

 '%b %d, %Y %I:%M:%S'

In [17]: print  datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %I:%M:%S')
2016-04-14 09:59:54

The -I is used only for strftime:

In [15]: print datetime.datetime.strptime("Apr 14, 2016 9:59:54", '%b %d, %Y %I:%M:%S').strftime('%b %d, %Y %-I:%M:%S')
Apr 14, 2016 9:59:54
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • 1
    `-I` in bash is to parse non-zero padded values, but `strptime` will parse regardless of zero padding, as per this answer: http://stackoverflow.com/questions/25279993/parsing-non-zero-padded-timestamps-in-python – Paulo Almeida Apr 14 '16 at 20:54