Search code examples
pythontimestrptime

time.strptime changing output formatting


I'm trying to change default output formatting of strptime and datetime in my functions:

   def start_week_date(year, week):
        format_string = "%i %i 1" % (int(year),int(week))
        start = time.strptime(format_string, '%Y %W %w')
        print datetime.date(start.tm_year, start.tm_mon, start.tm_mday)
        return datetime.date(start.tm_year, start.tm_mon, start.tm_mday)

output of which is being passed to another one:

for date_oncall in date_range(start_week_date(year,week), start_week_date(year,week+1)):
    print date_oncall

def date_range(start_date, end_date):
    """Generator of dates in between"""
    if start_date > end_date:
        raise ValueError("Start date is before end date.")
    while True:
        yield start_date
        start_date = start_date + datetime.timedelta(days=1)
        if start_date >= end_date:
            break

Is there an elegant way to change default formatting so if day of a month or a month is < 10 it doesn't get the '0' at the beginning? Basically instead of '03-05-2012' I would like to get '3-5-2012'.

Thanks much in advance for any suggestions.

Regards, Jakub


Solution

  • date objects have a method, strftime, to manually specify the format, but it doesn't have an option to do what you want - so, that means you need to construct the string yourself from the other attributes of date_oncall. The good news is that this is quite easy:

    >>> '{d.day}-{d.month}-{d.year}'.format(d=date_oncall)
    '17-1-2010'