Sometimes self.start is unicode:
eg.
>>>self.start
u'07:30:00'
Which makes datetime.combine complain
start = datetime.combine(self.job_record.date, self.start)
How does one:
- Test for unicode?
- Convert from u'07:30:00' to datetime.time?
Sometimes self.start is unicode:
eg.
>>>self.start
u'07:30:00'
Which makes datetime.combine complain
start = datetime.combine(self.job_record.date, self.start)
How does one:
Checking for unicode:
>>> import types
>>> type(u'07:30:00') is types.UnicodeType
True
>>> type('regular string') is types.UnicodeType
False
Converting strings to time:
>>> import time
>>> time.strptime(u'07:30:00', '%H:%M:%S')
(1900, 1, 1, 7, 30, 0, 0, 1, -1)
Assuming that there won't be extended charset characters in '07:30:00', then use str(self.start)
.
If there is a possibility that the numbers in the time are charset-specific, use encode()
, with an appropriate error
argument specifier to convert to string.
This may be a cases where it is more pythonic to try str()
first and use except
to handle cases that can't be converted (ask forgiveness rather than permission). If most of the values you are trying to convert fail, on the other hand, convert them first before applying the function.
As an unwanted aside: the combine
function expects a datetime.date object and a datetime.time object. If you really want to avoid unpredictable behaviour, then meet the requirements of the API and pass date
and time
objects, rather than trying to short-circuit the contract specified by the documentation: convert the arguments before you call combine
, rather than asking combine
to guess for you.
datetime.combine
is complaining because it expects the second argument to be a datetime.time
instance, not a string (or unicode string).
There are a few ways to convert your string to a datetime.time
instance. One way would be to use datetime.strptime
:
t = datetime.strptime(self.start, "%H:%M:%S").time()
start = datetime.combine(self.job_record.date, t)