Parsing non-zero padded timestamps in Python

后端 未结 5 1770
误落风尘
误落风尘 2020-12-05 01:39

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

The month, day o

相关标签:
5条回答
  • 2020-12-05 02:02

    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
    
    0 讨论(0)
  • 2020-12-05 02:05

    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")
    
    0 讨论(0)
  • 2020-12-05 02:12

    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
    
    0 讨论(0)
  • 2020-12-05 02:13

    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)
    
    0 讨论(0)
  • 2020-12-05 02:29

    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)
    
    0 讨论(0)
提交回复
热议问题