Parsing non-zero padded timestamps in Python




python time not zero padded (4)

strptime isdo not require 0-padded values. See example below

datetime.strptime("3/1/2014 9:55", "%m/%d/%Y %H:%M")
output:   datetime.datetime(2014, 3, 1, 9, 55)

I want to get datetimes from timestamps like the following :3/1/2014 9:55 with datetime.strptime, or something equivalent.

The month, day of month, and hour is not zero padded, but there doesn't seem to be a formatting directive listed here that is able to parse this automatically.

What's the best approach to do so? Thanks!


strptime is able to parse non-padded values. The fact that they are noted as being padded in the formatting codes table applies to strftime's output. So you can just use

datetime.strptime(datestr, "%m/%d/%Y %H:%M")

Just in case this answer helps someone else -- I came here thinking I had a problem with zero padding, but it was actually to do with 12:00 vs 00:00 and the %I formatter.

The %I formatter is meant to match 12-hour-clock hours, optionally zero-padded. But depending on your data source, you might get data that says that midnight or midday is actually zero, eg:

>>> datetime.strptime('2015/01/01 0:12am', "%Y/%m/%d %I:%M%p")
ValueError: time data '2015/01/01 0:12am' does not match format '%Y/%m/%d %I:%M'

What strptime actually wanted was a 12, not a zero:

>>> datetime.strptime('2015/01/01 12:12am', "%Y/%m/%d %I:%M%p")
datetime.datetime(2015, 1, 1, 0, 12)

But we don't always control our data sources! My solution for this edge case was to catch the exception, try parsing it with a %H, with a quick check that we are in the edge case we think we are in.

def get_datetime(string):
    try:
        timestamp = datetime.strptime(string, "%m/%d/%Y %I:%M%p")
    except ValueError:
        # someone used zero for midnight?
        timestamp = datetime.strptime(string, "%m/%d/%Y %H:%M%p")
        assert string.lower().endswith('am')
        assert timestamp.hour == 0
    return timestamp

You can see the strftime document here,but in fact they aren't all working well in all platforms,for instance,%-d,%-m don't work on win7 by python 2.7,so you can accomplish like this

>>> date_str = '{d.year}-{d.month}-{d.day}'.format(d=datetime.datetime.now())  
>>> print(date_str)
2016-5-23






datetime