Reputation: 1463
I was trying to create a dictionary with time stamp as the key. the code is :
>>> stamp = datetime.datetime(2012, 4, 12, 12, 26, int('13'))
>>> new_dict = {}
>>> new_dict[stamp] = 'one'
>>> print new_dict
{datetime.datetime(2012, 4, 12, 12, 26, 13): 'one'}
>>> print stamp
2012-04-12 12:26:13
Why does it not take the key as '2012-04-12 12:26:13' and instead taking the expression 'datetime.datetime()' as the key?
Upvotes: 0
Views: 273
Reputation: 9502
'2012-04-12 12:26:13' is a string, and stamp
in your example is a datetime.datetime
object.
You can use datetime objects directly as keys in a dictionnary, as stated in the documentation (two identical datetimes will have the same hash).
Upvotes: 2
Reputation: 65851
Because stamp
is a datetime.datetime
object. When you print
it, a string representing this object is printed. If you want a str
key, try
new_dict[str(stamp)] = 'one'
Upvotes: 2