Difference Between Two datetimes

Peter Otten __peter__ at web.de
Mon Dec 28 17:57:31 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?

Not "as though", it *is* a datetime object. And it knows how to show as 
something meaningful to the user when printed

These are very basic concepts that apply to all Python objects. I suggest 
that you take a moment to go through the tutorial before you continue with 
your efforts.

Peter



More information about the Python-list mailing list