Difference Between Two datetimes

W. eWatson wolftracks at invalid.com
Mon Dec 28 17:42:21 EST 2009


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?



More information about the Python-list mailing list