Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse unicode month name to get datetime in Python 2.7

I have a u'20 січня 2012' and I need to get datetime object. (u'20 січня 2012' == u'20 January 2012')

It's very easy when you have a datetime.strptime('1 Jun 2005', '%d %b %Y') But what to do if I have month in different locale ?

(appengine + python 2.7)

It would be good to have a method get_month(u'Month name in different forms', Language.RUS) -> int:'number of month' So the library could process different forms of month name. For example '1 Июнь' and '1 Июня' should be the same date. I'm using it for crawling websites and parsing date.

like image 757
Oleg Dats Avatar asked Jan 16 '12 19:01

Oleg Dats


People also ask

How do I print the month name in Python?

Method #1 : Using strftime() + %B In this, we use strftime() which converts date object to a string using a format, and by providing %B, it's enforced to just return a Month Name.

How do I get the month from a date in Python?

Method 1: Use DatetimeIndex. month attribute to find the month and use DatetimeIndex. year attribute to find the year present in the Date.

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.


2 Answers

Maybe you can convert it to a datetime object first, then use locale to set another locale and convert it again..

Here is something to get you starting..

import locale, datetime

In [1]: datetime.datetime.strptime('February', '%B')
Out[1]: datetime.datetime(1900, 2, 1, 0, 0)

In [2]: locale.setlocale(locale.LC_ALL, 'de_DE')
Out[2]: 'de_DE'

In [3]: datetime.date(2008, 2, 1).strftime('%B')
Out[3]: 'Februar'

In [4]: datetime.datetime.strptime('Februar', '%B')
Out[4]: datetime.datetime(1900, 2, 1, 0, 0)
like image 100
xeor Avatar answered Sep 21 '22 06:09

xeor


There is one good solution to use python_dateutil parse method and implement a parserinfo class for a given language.

http://blog.elsdoerfer.name/2009/12/12/django-flexible-date-form-fields-accepting-almost-any-input/

like image 37
Oleg Dats Avatar answered Sep 21 '22 06:09

Oleg Dats