strptime frisst kein Unicode, Workaround gesucht
Verfasst: Freitag 25. Mai 2012, 11:11
Hallo Liste, ich habe hier ein Problem an dem ich Noob mir die Zähne ausbeiße. Vielleicht kann mir ja jemand helfen.
Ich muss Zeitdaten aus einer Datei auswerten. Die Zeiten sehen etwa so aus:
Auftrag beendet am Mittwoch, 22. Februar 2012 um 21:45:40
Das kann ich gut auswerten mit time.strptime, nachdem die locale richtig gesetzt wurde.
Das Problem ist nun, dass die Variable im Unicode daherkommt und time.strptime damit nicht klarkommt:
Nach meinen Recherchen kann das nur mit einem Workaround umgangen werden, etwa so (von: http://grokbase.com/t/python/python-bug ... -de-locale):
Hier komme ich einfach nicht weiter! :K
Kann jemand helfen?
[Edit: bessere Verständlichkeit]
[Edit: noch ein Codebeispiel]
Ich muss Zeitdaten aus einer Datei auswerten. Die Zeiten sehen etwa so aus:
Auftrag beendet am Mittwoch, 22. Februar 2012 um 21:45:40
Das kann ich gut auswerten mit time.strptime, nachdem die locale richtig gesetzt wurde.
Das Problem ist nun, dass die Variable im Unicode daherkommt und time.strptime damit nicht klarkommt:
Code: Alles auswählen
>>> time.strptime("März", "%B")
time.struct_time(tm_year=1900, tm_mon=3, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=60, tm_isdst=-1)
>>> time.strptime(u"März", "%B")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 454, in _strptime_time
return _strptime(data_string, format)[0]
File "/usr/lib/python2.7/_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data u'M\xe4rz' does not match format '%B'
Das Problem ist nun, dass das nicht funktioniert wenn der Monat März drankommt, weil da ja ein Umlaut darin vorkommt (was ja das ursprüngliche Problem ist…):For anyone trying to work around this, unicode date strings
should be encoded to simple Python strings (type of str)
before passing into strptime. Here's an updated version of
the aforementioned test case demonstrating an acceptable
workaround:
Code: Alles auswählen
import locale, time locale.setlocale(locale.LC_TIME, 'de_DE') date = u'September'.encode() format = '%B' time.strptime(date, format)
Code: Alles auswählen
>>> import locale, time
>>> locale.setlocale(locale.LC_TIME, '')
'de_DE.UTF-8'
>>> date=u'September'.encode()
>>> date=u'März'.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 1: ordinal not in range(128)Kann jemand helfen?
[Edit: bessere Verständlichkeit]
[Edit: noch ein Codebeispiel]