Main Content

Month, Day, Year number to day of week and month names in Python - English and Swedish

Archive - Originally posted on "The Horse's Mouth" - 2016-06-23 07:03:24 - Graham Ellis

I had run a program (actually an answer to an exercise from our Lerning to program in Python course) which prints out a day and month number. And my group asked "how do I get the month by name?" and "What day of the week is that?"

Good questions ... and the answer in Python always starts ... "If you're doing something, think if someone's done it before, and if they have, the code probably exists and is available to you". With a common(ish) requirement, there's a probablility that the code you need is supplied as a module with the Python distribution, or is even built in via objects / methods / function calls.

Sample answer ... create a datetime object with the wanted day and month, and you can then enquire. Complete code is [here] ... the vital bits:

  dayinfo = datetime.date(year, moy[dayWanted-1], dom[dayWanted-1])
  print dayinfo.strftime("%B ... %A")


Then "Can you do that in Swedish?". Yes, if I set the locale before I do the formatting:

  import locale as l
  if not person in ("Gavin","Graham","Gary"):
    l.setlocale(l.LC_ALL, 'sv_SE')


(Ensuring that the results remain in English for the tutor, and delegates Gavin and Gary!)