Greg
Greg

Reputation: 1813

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.

Upvotes: 1

Views: 40

Answers (1)

alecxe
alecxe

Reputation: 474161

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)

Upvotes: 3

Related Questions