datetime iso8601 string input
aurora
aurora00 at gmail.com
Tue Mar 21 01:58:05 EST 2006
I agree. I just keep rewriting the parse method again and again.
wy
def parse_iso8601_date(s):
""" Parse date in iso8601 format e.g. 2003-09-15T10:34:54 and
returns a datetime object.
"""
y=m=d=hh=mm=ss=0
if len(s) not in [10,19,20]:
raise ValueError('Invalid timestamp length - "%s"' % s)
if s[4] != '-' or s[7] != '-':
raise ValueError('Invalid separators - "%s"' % s)
if len(s) > 10 and (s[13] != ':' or s[16] != ':'):
raise ValueError('Invalid separators - "%s"' % s)
try:
y = int(s[0:4])
m = int(s[5:7])
d = int(s[8:10])
if len(s) >= 19:
hh = int(s[11:13])
mm = int(s[14:16])
ss = int(s[17:19])
except Exception, e:
raise ValueError('Invalid timestamp - "%s": %s' % (s, str(e)))
return datetime(y,m,d,hh,mm,ss)
> I was a little surprised to recently discover
> that datetime has no method to input a string
> value. PEP 321 appears does not convey much
> information, but a timbot post from a couple
> years ago clarifies things:
>
> http://tinyurl.com/epjqc
>
>> You can stop looking: datetime doesn't
>> support any kind of conversion from string.
>> The number of bottomless pits in any datetime
>> module is unbounded, and Guido declared this
>> particular pit out-of-bounds at the start so
>> that there was a fighting chance to get
>> *anything* done for 2.3.
>
> I can understand why datetime can't handle
> arbitrary string inputs, but why not just
> simple iso8601 format -- i.e. the default
> output format for datetime?
>
> Given a datetime-generated string:
>
> >>> now = str(datetime.datetime.now())
> >>> print now
> '2006-02-23 11:03:36.762172'
>
> Why can't we have a function to accept it
> as string input and return a datetime object?
>
> datetime.parse_iso8601(now)
>
> Jeff Bauer
> Rubicon, Inc.
>
More information about the Python-list
mailing list