Reputation: 37
I'm trying to convert a string such as '2014-10-21 to 2014-10-23' to 'October 21-23, 2014' in Python. I already have a working version of this function, but it's extremely clunky.
import time
etime = '2014-10-21 to 2014-10-23'
time_pair = etime.split(' to ')
times = []
for i in time_pair:
trans_time = time.strptime(i, "%Y-%m-%d")
times.append(trans_time)
convert = []
for i in times:
foo = time.strftime("%B %d %Y", i)
convert.append(foo)
final = []
for i in convert:
final.append(i.split(' '))
eventer = final[0][0]
if final[0][0] == final[1][0]:
eventer = eventer[:] + ' ' + final[0][1] + '-' + final[1][1] + ', ' + final[0][2]
else:
eventer = eventer[:] + ' ' + final[0][1] + '-' + final[1][0] + ' ' + final[1][1] + ', ' + final[0][2]
How should could I improve this function?
Upvotes: 0
Views: 51
Reputation: 908
I improved it this way:
import calendar
etime = '2014-10-21 to 2014-10-23'
time_pair = etime.split(' to ')
dates = []
dates.append(time_pair[0].split('-'))
dates.append(time_pair[1].split('-'))
# Month = 1
Month1 = calendar.month_name[int(dates[0][1])] + ' '
Month2 = calendar.month_name[int(dates[1][1])] + ' '
if Month1 == Month2:
Month2 = ""
result = Month1 + dates[0][2] + '-'
result+= Month2 + dates[1][2] + ', ' + dates[0][0]
if dates[0][0] != dates[1][0]:
result += '-' + dates[1][0]
EDIT: While I was improving this, someone posted first. My hat is off to Peter Gibson, his solution is even better than mine.
Upvotes: 0
Reputation: 19564
import time
def format_date_range(etime):
input_date_strs = etime.split(' to ')
# use a list comprehension and tuple expansion
# typically 'i' is used for numbers, use of s hints at the items being strs
start, end = [time.strptime(s, "%Y-%m-%d") for s in input_date_strs]
# if both in the same year, omit it from start date
start_fmt = "%B %d" if start.tm_year == end.tm_year else "%B %d %Y"
# if both in the same month and year, omit month from end date
end_fmt = "%d, %Y" if (start.tm_mon, start.tm_year) == (end.tm_mon, end.tm_year) else "%B %d %Y"
return time.strftime(start_fmt, start)+ '-' + time.strftime(end_fmt, end)
TEST_TIMES = [
'2014-10-21 to 2014-10-23',
'2014-10-21 to 2015-10-23',
'2014-10-21 to 2014-11-23',
'2014-10-21 to 2015-10-23',
]
for etime in TEST_TIMES:
print format_date_range(etime)
Outputs:
October 21-23, 2014
October 21 2014-October 23 2015
October 21-November 23 2014
October 21 2014-October 23 2015
Upvotes: 2