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!

This should help you.

>>> import time
>>> date_old = '05/26/1999'
>>> time_tuple = time.strptime(date_old, "%m/%d/%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>
try:
    # use strptime(time_str, format_str) to form a time tuple
    time_tuple = time.strptime(date_old, fmt)
except: #Dont use bare except try to catch specific error that are comming
        #Example except ValueError or something else.
    pass

[EDIT] Nevermind, I got it. Turns out my definitions were wrong. Thanks for the help.

Here's the working code:

#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', '%m/%d/%y', '%m/%d/%Y %H:%M', '%d-%b-%Y %H:%M']
    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 KeyError:
            pass
        except ValueError:
            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)

date3 = "25-Jun-2010 13:15"
fn(date3)

Adaptation of the code I sent link to:

## request: #Function for converting date format from "5/14/1999 0:00" to "May-14", used further down
from datetime import date

for datestring in ['01/23/2010',"5/14/1999 0:00" ,'01.12.2020','1.1.1976',
                   ]:
    datestring,_,_=datestring.partition(' ')
    sep=[s for s in datestring if not s.isdigit()]

    if len(sep)!=2 or sep[0] != sep [1]: print "Mixup in separators",sep
    else:
##        print sep ## for testing
        datesep=sep[0]
        mm,dd,yy = (int(part) for part in datestring.split(datesep))
        print date(yy,mm,dd).strftime("%b-%d")
"""Output:
Jan-23
May-14
Jan-12
Jan-01
"""

I pretty much give you the answer.
"05/26/1999" should be covert to May-26,look at my first code.
Then rebuild your function with that code.
Get the function to work first then you can think of exception handling.

I see an other approach by tony using datetime module,that also work fine.
Tony can also use this format 01.12.2020.

For that to work we have to change like this in my code.

>>> date_old = '05.26.1999'
>>> time_tuple = time.strptime(date_old, "%m.%d.%Y")
>>> date_new = time.strftime("%b-%d", time_tuple)
>>> date_new
'May-26'
>>>

Or write something better that can handle both or more format.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.