简体   繁体   中英

Converting string to date not working

I just can't seem to get this to work - I'm pretty sure I've for the syntax for strptime() correct but its not working. The output expected is 31 Aug 2015 :

str = '31 Aug 2015 at 23:59'

try:
    mydate = datetime.strptime(str, '%d %b %Y')
    print mydate
except ValueError:
    mydate = None
    print "error"

I get "error" printed out. What am I missing?

The str variable is read from a file so it could have any data in it. I'm just looking for entries that have a valid date (Day Month Year) present.

You need to take into account the at 23:59 part too:

>>> from datetime import datetime
>>>
>>> s = '31 Aug 2015 at 23:59'
>>> datetime.strptime(s, "%d %b %Y at %H:%M")
datetime.datetime(2015, 8, 31, 23, 59)

Or, alternatively, let dateutil do the job:

>>> from dateutil.parser import parse
>>> 
>>> s = '31 Aug 2015 at 23:59'
>>> parse(s)
datetime.datetime(2015, 8, 31, 23, 59)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM