سؤال

If I cook this at an interactive prompt it returns one format - one I want at the moment.

But if I assign it to a variable and then print or use the variable like in the second example (same as in my file) it's in a different format.

How do I access the first output -

Thank you very much for any help.

import datetime
tote = datetime.timedelta(0, 25200), datetime.timedelta(0, 25200)
sum(tote, datetime.timedelta(0))
datetime.timedelta(0, 50400)


import datetime
tote = datetime.timedelta(0, 25200), datetime.timedelta(0, 25200)
brac = sum(tote, datetime.timedelta(0))
print brac
14:00:00



import datetime
tote = datetime.timedelta(0, 25200), datetime.timedelta(0, 25200)
brac = sum(tote, datetime.timedelta(0))
print repr(brac)
datetime.timedelta(0, 50400)
datetime.timedelta.total_seconds(repr(brac))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'total_seconds' requires a 'datetime.timedelta' object but 
received a 'str'
هل كانت مفيدة؟

المحلول

The Python interactive shell echos the results of expressions using the repr() function, but print uses str() to convert values to a string.

In both cases sum() produces the exact same result, but in your first sample, you see the interpreter print the output with repr(), in your second result you used print and the result was converted to a string with str():

>>> import datetime
>>> tote = datetime.timedelta(0, 25200), datetime.timedelta(0, 25200)
>>> brac = sum(tote, datetime.timedelta(0))
>>> brac
datetime.timedelta(0, 50400)
>>> print brac
14:00:00
>>> repr(brac)
'datetime.timedelta(0, 50400)'

There is nothing else you need to do; you already have the same result assigned to brac.

نصائح أخرى

When you say print brac, you're accessing the object's string representation. What you probably want is print repr(brac), which gives you the format as produced by your first code example.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top