I've got a couple strings from which I want to get the datetime. They are formatted like this:
Thu 2nd May 2013 19:00
I know almost how I can convert this to a datetime, except for that I'm having trouble with the "2nd". I now have the following
>>> datetime.strptime('Thu 02 May 2013 19:00', '%a %d %B %Y %H:%M')
datetime.datetime(2013, 5, 2, 19, 0)
which works fine with a zero padded number for the day of the month, but when I try the 2nd
, it gives a ValueError:
>>> datetime.strptime('Thu 2nd May 2013 19:00', '%a %d %B %Y %H:%M')
Traceback (most recent call last):
File "<input>", line 1, in <module>
(data_string, format))
ValueError: time data 'Thu 2nd May 2013 19:00' does not match format '%a %d %B %Y %H:%M'
In the list of datetime directives I can't find anything relating to ordered values (1st, 2nd, 3rd etc) for dates. Does anybody know how I can get this to work? All tips are welcome!
Consider using
dateutil.parser.parse
.It's a third party library that has a powerful parser which can handle these kinds of things.
A brief caveat (doesn't really occur in your case): if
dateutil
can't find an aspect of your date in the string (say you leave out the month) then it will default to thedefault
argument. This defaults to the current date with the time 00:00:00. You can obviously over-write this if necessary with a differentdatetime
object.The easiest way to install
dateutil
is probably usingpip
with the commandpip install python-dateutil
.You can preparse the original string to adjust the day to be suitable for your
strptime
, eg:It's straightforward to remove the suffix from the date without using regular expressions or an external library.
Then it's as simple as using
strptime
as you'd expect: