0

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?

2 Answers 2

2

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'
Sign up to request clarification or add additional context in comments.

Comments

2

'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).

1 Comment

can i use it like: new_dict[datetime.datetime()] ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.