I’d like to format a string with two datetimes, using a particular format.
d1 = datetime.datetime.now()
d2 = datetime.datetime.now() - datetime.timedelta(days=1)
daterange = [d1, d2]
fmt = '%Y/%m/%d %H:%M:%S'
I’m currently formatting the dates with strftime first:
string = "Date range: {} to {}".format(d1.strftime(fmt), d2.strftime(fmt))
Date range: 2013/02/05 12:22:12 to 2013/02/04 12:22:12
Is there a cleaner way?
You can supply the date format in the string itself:
Following on from this, it’s a bit cleaner if we set the format from a parameter to
format():And we can even pass a single date range, and get all the dates from there using
0[index]We could also use named fields, for more readability: