Python 3 dealing with special French characters

I am trying to  create a French oriented date ( eg  août 2, 2015 - that's August 2, 2015 for those of you who are lousy at French, like me.  I am attaching the  code which gets me there with respect to the format - thanks to help from CLOCKWATCHER.
 However I have now realize that Python 3 does not l like working with special characters (like /  \ û..). So the best I can get is the correct format, but without the special characters.  I've looked at the Python documentation in this area but its very hard to comprehend.   Hopefully there is someone who  has an expertise  in this !!

#!C:\Python34\python.exe
import cgi,cgitb
import mysql.connector as conn
import collections
import datetime
def htmlTop():
    print("""Content-type:text/html\n\n
        <!DOCTYPE html>
        <html lang="en">
            <head>
                #<meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1">
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <title> My Server-side template</title>
        </head>
        <body>""")

def htmlTail():
    print(""" its done</body>
        </html>""")

def connectDB():
    db=conn.connect(host='localhost' ,user='root' ,passwd='844cheminduplan' ,db='office')
    cursor = db.cursor()
    return db, cursor 


#main program
if __name__== "__main__":
    try:
        htmlTop()
        
        datetime.datetime.time(datetime.datetime.now())
        print(datetime.datetime.time(datetime.datetime.now()), "this is just the time")
        now = datetime.datetime.now()
        print(now, "- this is all the date info")
        year = now.year
        print (year, "- year from now.year")
        month = now.month
        print(month,"- month from now.month")
        day = now.day
        print(day,"- day from now.day")
        # PRINTING THE DATE IN FORMAT Janvier 3, 2015 - which is correct for France. (vrs 3, January, 2015 for english)
        # NOTE DOES NOT WORK AT THE MOMENT IF YOU USE SPECIAL CHARACTERS - even within # !!!       
        months = ('janvier', 'fevrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'aout', 'septembre', 'octobre', 'novembre', 'decembre')
        print("{month} {day}, {year}".format(month=months[now.month-1], day=now.day, year=now.year))
    except:
        cgi.print_exception()

Open in new window

jameskaneAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

peprCommented:
Try the following sample:
#!python3
import datetime
import locale

def htmlTop():
    return """<!DOCTYPE html>
        <html>
        <head>
                <meta charset="UTF-8">
                <title> My Server-side template</title>
        </head>
        <body>"""

def htmlTail():
    return """</body>
        </html>"""


if __name__ == "__main__":
    locale.setlocale(locale.LC_ALL, 'french')
    with open('output.html', 'w', encoding='utf-8') as f:
        f.write(htmlTop())
        now = datetime.datetime.now()
        s = now.strftime('%B %d, %Y')
        f.write(s)
        f.write(htmlTail())

Open in new window


It generates the output.html. When opened, the browser should display the date as you want. However, the day is zero padded.

If you want to use your dict approach, it should work just fine. Possibly, check whether you save your source code in UTF-8. The problem can be with print as it tries to convert the UNICODE string to the encoding of the console. If you use cmd it usually does not use UNICODE, or it does not have the font with all character.
jameskaneAuthor Commented:
Thanks pepr for the response.

As I understand it, if  I run the code you sent, it should generate a file -  output.html. However, I get an error message as attached. I ran it as a .cgi file and attach the code (which is of course a direct copy of what you sent.

Thanks very much for taking the time on this.


#!python3
import datetime
import locale

def htmlTop():
    return """<!DOCTYPE html>
        <html>
        <head>
                <meta charset="UTF-8">
                <title> My Server-side template</title>
        </head>
        <body>"""

def htmlTail():
    return """</body>
        </html>"""


if __name__ == "__main__":
    locale.setlocale(locale.LC_ALL, 'french')
    with open('output.html', 'w', encoding='utf-8') as f:
        f.write(htmlTop())
        now = datetime.datetime.now()
        s = now.strftime('%B %d, %Y')
        f.write(s)
        f.write(htmlTail())

Open in new window

frenchspecialchar.jpg
peprCommented:
I do not have experience with CGI scripts (the things around). In the case, you should use print instead of the f.write. If the generated output.html worked for you, the result generated by the CGI script should also work. You should not use the if __name__ == '__main__': as it is valid only if the script is launched on its own -- as executable or via the interpreter directly, not as a module.

print('Content-Type: text/html')
print()
print('''<!DOCTYPE html>
<html>
<head>
  <title> My Server-side template</title>
  <meta charset="UTF-8">
</head>
<body>''')

locale.setlocale(locale.LC_ALL, 'french')
now = datetime.datetime.now()
s = now.strftime('%B %d, %Y')   
print(s)
print('</body>\n</html>')

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
jameskaneAuthor Commented:
Ok pepr, that will get me started in the right direction !!

tks

james
peprCommented:
There may be one hidden problem with CGI and the print command. The print converts internally the string to the encoding used by the output device (console). It means, that it asks the output device somehow to know the encoding. The CGI binds the print command to the engine. This way the engine should give the print the encoding. If there is any misunderstanding (different encoding than expected), the characters can be wrongly encoded (than what is said by the meta charset in the HTML doc).
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Python

From novice to tech pro — start learning today.