我需要将一些输入信息存储为字典中的值。将输入存储在时间戳键下非常方便。我试着这样做:
from datetime import datetime
date = '%s.%02d.%sX%s%s%s' % (when.day, when.month, when.year, when.minute, when.second, when.microsecond) #
someDict = {}
for iter in range(5):
someValue = raw_input('Value:')
print date
someDict[date] = someValue
结果我有:
Value: 11111
12.07.2014X3456671342
Value: 22222
12.07.2014X3456671342
Value: 33333
12.07.2014X3456671342
Value: 44444
12.07.2014X3456671342
Value: 55555
12.07.2014X3456671342
当然,len(someDict)
是1
,而不是5
。
完美的输出应该是这样的:
someDict = {'12.07.2014X-----': 11111, '12.07.2014X-----': 22222, '12.07.2014X-----': 33333} #Where ----- is a time-based number.
依此类推,能够添加新的键/值
答案 0 :(得分:2)
你的意思是这样的:
from datetime import datetime
from time import sleep
d = {}
val = 0
while True:
sleep(1)
now = datetime.now().strftime('%s')
d[now] = val
val += 1
print(d)
这样的事情可能有用并不意味着将datetime对象用作dict键是明智的。
也许最好将您的值作为带有时间戳的元组添加到列表中;这样你就知道了价值的来源和时间:
from datetime import datetime
from time import sleep
data = []
val = 0
for i in range(100):
sleep(.001)
now = datetime.now().strftime('%s')
data.append((val, now))
val += 1
print(data)
答案 1 :(得分:2)
看看是否有效
import datetime
someDict = {}
for iter in range(5):
date_now = datetime.datetime.utcnow()
date = '%s.%02d.%sX%s%s%s' % (date_now.day, date_now.month, date_now.year, date_now.minute, date_now.second, date_now.microsecond) #
someValue = raw_input('Value:')
print date
someDict[date] = someValue
答案 2 :(得分:0)
怎么样
from datetime import datetime
date = '%s.%02d.%sX%s%s%s' % (when.day, when.month, when.year, when.minute, when.second, when.microsecond) #
someDict = {}
old_date = None
counter = 0
for iter in range(5):
if old_date != date:
counter = 0
old_date = date
key = '%s%08d' % (date, counter)
counter += 1
someValue = raw_input('Value:')
print key
someDict[key] = someValue