Based on the locale I need to find what is the first day of the week (Sunday/Monday) In JAVA I would do:
Calendar FR_cal = Calendar.getInstance(Locale.FRANCE);
Calendar CA_cal = Calendar.getInstance(Locale.CANADA);
DateFormatSymbols dfs = new DateFormatSymbols();
String weekdays[] = dfs.getWeekdays();
System.out.println(weekdays[JO_cal开发者_运维问答.getFirstDayOfWeek()]);
System.out.println(weekdays[FR_cal.getFirstDayOfWeek()]);
How can I do it in python ?
I could only figure out how to do this with the Babel library. It's available through easy_install
.
>>> import babel
>>> locale = babel.Locale('en', 'US')
>>> locale.first_week_day
6
>>> locale.days['format']['wide'][locale.first_week_day]
u'Sunday'
turns out that the following doesn't work as Nate was kind enough to point out. If anybody knows why, please post and answer showing how to do it right. This should be doable with the standard library.
If you just want the number of the day, then you can use calendar.LocalTextCalendar
.
>>> import calendar
>>> c = calendar.LocaleTextCalendar(locale='de_DE') # locale=('en_US', 'UTF8') fails too.
>>> c.firstweekday
0
There is also the iterweekdays
method.
>>> list(c.iterweekdays())
[0, 1, 2, 3, 4, 5, 6]
This functionality seems to be missing from the python standard library up to and including (at least) Python 3.1.2.
Some clues:
Since information about this is usually stored along with the systems l10n data (in the GNU world that would be the locale def's likely in /usr/share/i18n/locales/
) my first reaction was to use something like locale.nl_langinfo()
, but unfortunately there is nothing like locale.FIRST_WEEKDAY
in the locale module :-(
Aside from the Babel lib mention by aaronasterling, I found this example of a solution for the named problem used inside a GNOME applet. Also worth noting is the accompanying blog post.
Calendars in many European countries, in particular, now follow the ISO decision by starting the week on Monday. Airline timetables also number the days from Monday as 1, Tuesday as 2, Wednesday as 3, etc.
The above states that Monday should always be the first day of the week.
Take a look at the calendar module. Might come handy for this!
精彩评论