Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

python time string does not match format

def deadlines(t):
    '''shows pretty time to deadlines'''
    fmt = '%a %d %m %Y %I:%M %p %Z' 

    dt = datetime.strptime( t , fmt )

    print 'dt ', repr(dt)


first = 'Sun 11 May 2014 05:00 PM PDT'
deadlines(first)

ValueError: time data 'Sun 11 May 2014 02:00 PM PDT' does not match format ' %a %d %m %Y %I:%M %p %Z '

Whats wrong with this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

%m matches months represent as a two-digit decimal (in [01, 12]). Use %b for abbreviated month names, or %B for full month names instead:

fmt = '%a %d %b %Y %I:%M %p %Z'

A table showing the date format directives and their meanings can be found here.


If you're having trouble parsing PDT using %Z:

Per the time.strptime docs:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

So, if parsing the date string without PDT works:

In [73]: datetime.strptime('Sun 11 May 2014 05:00 PM', '%a %d %b %Y %I:%M %p')
Out[73]: datetime.datetime(2014, 5, 11, 17, 0)

but

datetime.strptime('Sun 11 May 2014 05:00 PM PDT', '%a %d %b %Y %I:%M %p %Z')

raises a ValueError, then you may need strip off the timezone name (they are, in general, ambiguous anyway):

In [10]: datestring = 'Sun 11 May 2014 05:00 PM PDT'

In [11]: datestring, _ = datestring.rsplit(' ', 1)

In [12]: datestring
Out[12]: 'Sun 11 May 2014 05:00 PM'

In [13]: datetime.strptime(datestring, '%a %d %b %Y %I:%M %p')
Out[13]: datetime.datetime(2014, 5, 11, 17, 0)

or use dateutil:

In [1]: import dateutil.parser as parser

In [2]: parser.parse('Sun 11 May 2014 05:00 PM PDT')
Out[2]: datetime.datetime(2014, 5, 11, 17, 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...