Hi. I need some help here with a unicode string I want to use with strptime.

>>> date
u'\xa08/15/2009'
>>> datetime.strptime(date, "%m/%d/%Y")
Traceback (most recent call last):
  File "<pyshell#75>", line 1, in <module>
    datetime.strptime(date, "%m/%d/%Y")
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)

Thanks for your time.

Recommended Answers

All 2 Replies

See if is this what you want:

import time
time.strftime("%m/%d/%Y", time.localtime())

If it isnt try this website, it probably will help you:
http://docs.python.org/library/datetime.html

Dan08.

Hello there. I don't think you understood what I meant. I already have a date in a string variable I want to use with strptime. The problem is really the encoding.

In the meanwhile, I searched the internet for what '\xa0' was an discovered it is the &nbsp; from HTML. That character is not part of ASCII and therefore there's an encoding error. What I did was to erase that '\xa0' char I don't want, and then encode the string in ASCII and I was all set to call strptime now.

Here's how I did it:

date = date.replace(u'\xa0', '') # removes \xa0 char (&nbsp)
date = date.encode() # encode to asccii from unicode
date = datetime.strptime(date, "%m/%d/%Y")

Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.