Problems with datetime.datetime.strptime

Tuomas Vesterinen tuomas.vesterinen at iki.fi
Sat May 9 04:57:48 EDT 2009


I hoped that I could get rid of my special module _strptime2 when 
porting to Python 3.0. But testing is a disappointment.

Python 3.0.1 (r301:69556, Apr 14 2009, 14:30:31)
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> import locale, datetime
 >>> def test1(locale_str, val):
...     print(locale.setlocale(locale.LC_ALL, locale_str), ':')
...     test_cases = [
...         locale.nl_langinfo(locale.D_T_FMT), # test default formats
...         locale.nl_langinfo(locale.D_FMT),
...         locale.nl_langinfo(locale.T_FMT)
...     ]
...     for form in test_cases:
...         string = val.strftime(form)
...         print("  strftime(%s)=%s" % (repr(form), repr(string)))
...         print("  strptime(%s,%s)=" % (repr(string), repr(form)), 
end=' ')
...         try:
...             val2 = datetime.datetime.strptime(string, form)
...         except ValueError as e:
...             print('\n   ', str(e))
...         else:
...             print('\n   ', str(val2))
...
 >>> now = datetime.datetime.now()
 >>> for loc in ('C', 'en_US.UTF-8', 'fi_FI.UTF-8'):
...     test1(loc, now)
...
C :
   strftime('%a %b %e %H:%M:%S %Y')='Sat May  9 11:26:12 2009'
   strptime('Sat May  9 11:26:12 2009','%a %b %e %H:%M:%S %Y')=
     'e' is a bad directive in format '%a %b %e %H:%M:%S %Y'
   strftime('%m/%d/%y')='05/09/09'
   strptime('05/09/09','%m/%d/%y')=
     2009-05-09 00:00:00
   strftime('%H:%M:%S')='11:26:12'
   strptime('11:26:12','%H:%M:%S')=
     1900-01-01 11:26:12
en_US.UTF-8 :
   strftime('%a %d %b %Y %r %Z')='Sat 09 May 2009 11:26:12 AM '
   strptime('Sat 09 May 2009 11:26:12 AM ','%a %d %b %Y %r %Z')=
     'r' is a bad directive in format '%a %d %b %Y %r %Z'
   strftime('%m/%d/%Y')='05/09/2009'
   strptime('05/09/2009','%m/%d/%Y')=
     2009-05-09 00:00:00
   strftime('%r')='11:26:12 AM'
   strptime('11:26:12 AM','%r')=
     'r' is a bad directive in format '%r'
fi_FI.UTF-8 :
   strftime('%a %e. %Bta %Y %T')='la  9. toukokuuta 2009 11:26:12'
   strptime('la  9. toukokuuta 2009 11:26:12','%a %e. %Bta %Y %T')=
     'e' is a bad directive in format '%a %e. %Bta %Y %T'
   strftime('%d.%m.%Y')='09.05.2009'
   strptime('09.05.2009','%d.%m.%Y')=
     2009-05-09 00:00:00
   strftime('%T')='11:26:12'
   strptime('11:26:12','%T')=
     'T' is a bad directive in format '%T'

What to do.
Tuomas Vesterinen



More information about the Python-list mailing list