Difference Between Two datetimes

Steve Holden steve at holdenweb.com
Tue Dec 29 08:46:19 EST 2009


W. eWatson wrote:
> Peter Otten wrote:
>> W. eWatson wrote:
>>
>>> This is quirky.
>>>
>>>  >>> t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S")
>>>  >>> t1
>>> datetime.datetime(2009, 12, 5, 22, 11)
>>>  >>> type(t1)
>>> <type 'datetime.datetime'>
>>>  >>>
>>> t1:  2009-12-05 22:11:00 <type 'datetime.datetime'>
>>>
>>> but in the program:
>>>     import datetime
>>>
>>>     t1=datetime.datetime.strptime("20091205_221100","%Y%m%d_%H%M%S")
>>>     print "t1: ",t1, type(t1)
>>>
>>> produces
>>> t1:  2009-12-05 22:11:00 <type 'datetime.datetime'>
>>>
>>> Where did the hyphens and colons come from?
>>
>> print some_object
>>
>> first converts some_object to a string invoking str(some_object) which
>> in turn calls the some_object.__str__() method. The resulting string
>> is then written to stdout. Quoting the documentation:
>>
>> datetime.__str__()
>>     For a datetime instance d, str(d) is equivalent to d.isoformat(' ').
>>
>> datetime.isoformat([sep])
>>     Return a string representing the date and time in ISO 8601 format,
>>     YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0,
>> YYYY-MM-DDTHH:MM:SS
>>
>> Peter
> So as long as I don't print it, it's datetime.datetime and I can make
> calculations or perform operations on it as though it is not a string,
> but a datetime object?

It's nothing to do with whether you print it or not. When you print it,
an equivalent string is produced, and the string is what gets printed.
This is necessary, because humans only understand character-based output.

>>> type(x)
<type 'float'>
>>> print x
82.2
>>> type(x)
<type 'float'>

The type of something is unchanged by printing it. The print statement
merely calls methods of the object to produce strings that it can print.

>>> x.__str__()
'82.2'
>>> x.__repr__()
'82.200000000000003'
>>>

People talk loosely about "converting an object to a string", but that
doesn't mean transmogrifying the object to something else, it means
producing an equivalent value of some other type which can be used
instead of the original object for some specific purpose. In this case,
printing.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/




More information about the Python-list mailing list