Parsing non-zero padded timestamps in Python

Question:

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!

Asked By: Pythontology

||

Answers:

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")
Answered By: Jason S

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)
Answered By: gaw

The non-pattern way is use dateutil.parse module, it lets to parse the common date formats, even if you don’t know what it is using currently

Ex:

>>> import dateutil.parser
>>> 
>>> utc_time     = '2014-08-13T00:00:00'
>>> verbose_time = '13-Aug-2014'
>>> some_locale  = '3/1/2014 9:55'
>>> dateutil.parser.parse(utc_time)
datetime.datetime(2014, 8, 13, 0, 0)
>>> dateutil.parser.parse(verbose_time)
datetime.datetime(2014, 8, 13, 0, 0)
>>> dateutil.parser.parse(some_locale)
datetime.datetime(2014, 3, 1, 9, 55)
Answered By: xecgr

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
Answered By: hwjp

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
Answered By: 黄东辉
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.