4

I need to parse polish date from string like this:

locale.setlocale(locale.LC_TIME, 'pl_PL.utf8')
print(time.strptime("27 luty 13:00:00", '%d %B %H:%M:%S'))

Actually above works fine, but the polish language dates are not as trivial as english one. The valid date in polish language is this:

27 lutego 13:00:00

Unfortunately strptime fails printing:

ValueError: time data '27 lutego 13:00:00' does not match format '%d %B %H:%M:%S'

What's the fool-proof solution for parsing dates from different locales?

4
  • 1
    Here's a link to a similar SO question that could be useful stackoverflow.com/questions/3654423/… Commented Feb 16, 2014 at 20:15
  • (I don't know polish) It looks like "luty" is short for "lutego", and might take the %b format, not %B? Commented Feb 16, 2014 at 20:16
  • My fault, I should introduce the language first. Both "luty" and "lutego" are correct full name for months. Quoting: 'Polish grammar has 7 grammatical cases. Endings of nouns change depending on the number, gender and case of that noun' In German there is some sort of similar thing namely: "Deklination der Substantive". In english fortunately there is no such a thing. BTW. Tried %b, but it does not work as I supposed. Commented Feb 16, 2014 at 21:30
  • According to that link: stackoverflow.com/questions/3654423/… There is parse_datetime in Babel, but it looks that this method does not exists in V1.* that I use. It was in oldver version. I could find parse_date and parse_time only. Commented Feb 16, 2014 at 21:34

1 Answer 1

1

You could use a lookup table:

lookup_table = {
    "stycznia": "styczeń",   "lutego": "luty",
    "marca": "marzec",       "kwietnia": "kwiecień",
    "maja": "maj",           "czerwca": "czerwiec",
    "lipca": "lipiec",       "sierpnia": "sierpień",
    "września": "wrzesień",  "października": "październik",
    "listopada": "listopad", "grudnia": "grudzień"
}
s = "27 lutego 13:00:00"
for k, v in lookup_table.items():
    s = s.replace(k, v)

locale.setlocale(locale.LC_TIME, "pl_PL.utf8")
result = time.strptime(s, "%d %B %H:%M:%S")    # time.struct_time(tm_year=1900, tm_mon=2, tm_mday=27, tm_hour=13, 
                                               #                  tm_min=0, tm_sec=0, tm_wday=1, tm_yday=58, tm_isdst=-1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.