简体   繁体   English

Python datetime时间戳问题

[英]Python datetime timestamp issue

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? 为什么不将键设为“ 2012-04-12 12:26:13”,而将表达式“ datetime.datetime()”作为键?

Because stamp is a datetime.datetime object. 因为stampdatetime.datetime对象。 When you print it, a string representing this object is printed. 当您print它时,代表该对象的字符串将被打印。 If you want a str key, try 如果您想要一个str键,请尝试

new_dict[str(stamp)] = 'one'

'2012-04-12 12:26:13' is a string, and stamp in your example is a datetime.datetime object. “ 2012-04-12 12:26:13”是字符串,示例中的stampdatetime.datetime对象。

You can use datetime objects directly as keys in a dictionnary, as stated in the documentation (two identical datetimes will have the same hash). 文档中所述,您可以将datetime对象直接用作字典中的键(两个相同的datetime将具有相同的哈希值)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM