Peter S
Peter S

Reputation: 575

Converting Date to String (strftime) in one Line

There's a dictionary data with Date as key. I'd like to get the max Date from the Dictionary and convert it to a string with a slightly different form: . instead of - between %Y-%m-%d and changing the order of %Y and %d

This is how I did it:

date_maximal = max(datum for datum in data.keys())
date_maximal = datetime.datetime.strptime(date_maximal,"%Y-%m-%d %H:%M")
date_maximal = date_maximal.strftime("%d.%m.%Y %H:%M")

Is there an option cram this into one line?

Upvotes: 0

Views: 867

Answers (1)

Aaron Christiansen
Aaron Christiansen

Reputation: 11807

I think this should work:

datetime.datetime.strptime(max(datum for datum in data.keys()), "%Y-%m-%d %H:%M").strftime("%d.%m.%Y %H:%M")

This appears to be the quickest way to convert a date into a different format.

Upvotes: 1

Related Questions