Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing date string in Python

Tags:

python

string

How can I rewrite following clause:

if u'января' in date_category['title']:
    month = 1
elif u'февраля' in date_category['title']:
    month = 2
elif u'марта' in date_category['title']:
    month = 3
elif u'апреля' in date_category['title']:
    month = 4
elif u'мая' in date_category['title']:
    month = 5
elif u'июня' in date_category['title']:
    month = 6
elif u'июля' in date_category['title']:
    month = 7
elif u'августа' in date_category['title']:
    month = 8
elif u'сентября' in date_category['title']:
    month = 9
elif u'октября' in date_category['title']:
    month = 10
elif u'ноября' in date_category['title']:
    month = 11
elif u'декабря' in date_category['title']:
    month = 12

It just looks ugly.

like image 997
evgeniuz Avatar asked Dec 06 '22 15:12

evgeniuz


1 Answers

To solve this, parse your date information using the python datetime module. It has support for locales, and will sort this out. If genitive forms are really the issue, then just map those forms to the dative, then map back on output.

To answer your actual question -

Consider that you are pairing up data with integers. If you can transform your data into the format (month, integer), you can drive your code with data.

for (n, month) in enumerate(u'января, feb, mar, apri, may, jun, jul, aug, sep, oct, nov, декабря'.split(', '), 1):# the parameter 1 specifies to start counting from 1. h/t @san4ez
    if month in date_category['title']: return n
like image 143
Marcin Avatar answered Dec 09 '22 16:12

Marcin