Reputation: 109
I need to store some input information as a value in a dictionary. It will be very convenient to store the input under a timestamp key. I try this for example:
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
As a result i have:
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
And, of course, the len(someDict)
is 1
, instead of 5
needed.
The perfect output should be something like:
someDict = {'12.07.2014X-----': 11111, '12.07.2014X-----': 22222, '12.07.2014X-----': 33333} #Where ----- is a time-based number.
And so on, with an ability to add new Key/Values
Upvotes: 0
Views: 1106
Reputation: 6418
Do you mean like this:
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)
That something like this might work doesn't mean it's wise to use datetime objects as dict keys..
Maybe it would be better to add your values to a list as tuples with a timestamp; that way you know both the order in which the values came in and the time:
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)
Upvotes: 2
Reputation: 781
See if this works
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
Upvotes: 2
Reputation: 133879
How about
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
Upvotes: 0