I need a function which can take in a variety of time formats like "05/26/1999" and "02/14/2010 12:44" and convert them into this format: May-26 or Feb-14.
I've tried to do this, but without success. Here's the code I tried (with some prints included for debugging purposes):
#Function for converting date format from "5/14/1999 0:00" to "May-14", used further down
import time
#This function takes in a date of a form like "5/14/1999 0:00" and turns it into a usable date like May-14
def fn(date_old):
format_list = ['%m/%d/%Y %h:%M', '%m/%d/%y']
done = False
for fmt in format_list:
try:
# use strptime(time_str, format_str) to form a time tuple
time_tuple = time.strptime(date_old, fmt)
except:
pass
else:
done = True
break
if done:
#print(time_tuple) # test
# use time.strftime(format_str, time_tuple) to create new format
#%b is "Locale's abbreviated month name." Like Jan, Feb, Mar, etc.
date_new = time.strftime("%b-%d", time_tuple)
print date_new
return date_new
else:
for fmt in format_list:
print fmt
print date_old
print 'Not a valid time format'
#Convert the report into a grid using list comprehensions
grid = [[x.strip() for x in row.split(',')] for row in filelines]
date1 = "05/26/1999"
fn(date1)
date2 = "02/14/2010 12:44"
fn(date2)
While it should've returned the right format, this is what actually came out:
%m/%d/%Y %h:%M
%m/%d/%y
05/26/1999
Not a valid time format
%m/%d/%Y %h:%M
%m/%d/%y
02/14/2010 12:44
Not a valid time format
Any help as to what I'm doing incorrectly would be largely appreciated. Thanks!