Reputation: 1141
I have a time format:
Sat Jan 17 04:33:06 +0000 2015
that I can't match to a strptime format. The closest I can find: basic datetime types is %c "Locale’s appropriate date and time representation." However, this doesn't exactly match.
I'm going for:
time_vec = [datetime.strptime(str(x),'%c') for x in data['time']]
any help would be appreciated.
Upvotes: 1
Views: 1239
Reputation: 881477
Works fine for me...:
>>> s='Sat Jan 17 04:33:06 +0000 2015'
>>> f='%a %b %d %X %z %Y'
>>> import datetime
>>> datetime.datetime.strptime(s,f)
datetime.datetime(2015, 1, 17, 4, 33, 6, tzinfo=datetime.timezone.utc)
This is in Python 3.4. In Python 2.7, I can reproduce your bug -- it doesn't accept the %z
as it should. The best workaround is to upgrade to Python 3, of course. If you just can't, you need some hack like:
import re
s = re.sub('[+-]\d+', '', s)
and remove the %z
from the format. If you do need that timezone info, extract it first (with a re.search
, same pattern) before the re.sub
to "clean up" s
to work around the Python 2 bug.
Upvotes: 6
Reputation: 50540
>>> from dateutil import parser
>>> s = "Sat Jan 17 04:33:06 +0000 2015"
>>> dt = parser.parse(s)
>>> dt
datetime.datetime(2015, 1, 17, 4, 33, 6, tzinfo=tzutc())
This is using the dateutil package to parse your string and return a datetime object.
Side note: The bug you reference indicates that the problem is resolved in Python 3.2. My assumption is that you are not using Python 3, thus have the error.
Upvotes: 3