1

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.

secumind
  • 1,141
  • 1
  • 17
  • 38
  • I assume I can do something like: %a %b %d %X %z %Y but It doesn't seem to work, I end up with "ValueError: 'z' is a bad directive in format '%a%b%d%X%z%Y'" – secumind Jan 17 '15 at 05:11
  • Before anyone points out that this is a known issue http://bugs.python.org/issue6641 I am aware... However that doesn't actually provide an answer. I still need to be able to handle this date format. – secumind Jan 17 '15 at 05:25
  • have you seen: [Python strptime() and timezones?](http://stackoverflow.com/q/3305413) or [How do I parse timezones with UTC offsets in Python?](http://stackoverflow.com/q/1302161/4279) – jfs Jan 17 '15 at 15:10
  • related: [How to parse dates with -0400 timezone string in python?](http://stackoverflow.com/q/1101508/4279) – jfs Jan 17 '15 at 15:18
  • related: [Convert timestamps with offset to datetime obj using strptime](http://stackoverflow.com/q/12281975/4279) – jfs Jan 17 '15 at 15:21

2 Answers2

6

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.

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
  • the format expects a locale-dependent string (`%b`, `%X`). It might fail to parse the input if non-English locale is enabled. – jfs Jan 17 '15 at 15:24
3
>>> 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.

Andy
  • 49,085
  • 60
  • 166
  • 233