topless
topless

Reputation: 8221

How can I retrieving a timestamp from a dictionary and converting it to datetime object?

I have a dictionary of timestamps in this form 2011-03-01 17:52:49.728883 and ids. How can I retrieve the latest timestamp and represent it in python datetime object?

The point is to be able to use the latest date of the timestamp instead of the currnt date in above code.

latest = datetime.now()

Upvotes: 1

Views: 1178

Answers (1)

NPE
NPE

Reputation: 500227

The structure of your dictionary is not entirely clear from your question, so I'll assume the keys are strings containing timestamps like the one in your question.

If d is the dictionary:

datetime.strptime(max(d.keys()),'%Y-%m-%d %H:%M:%S.%f')

The above code uses the fact that the lexicographical ordering of your datetime strings sorts timestamps in chronological order. If you'd rather not rely on that, you could use:

max(map(lambda dt:datetime.strptime(dt,'%Y-%m-%d %H:%M:%S.%f'),d.keys()))

Upvotes: 2

Related Questions