HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Transforming tuple with (int month, int year) in string "mm/yyyy"

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yearwithyyyytransformingtuplemonthintstring

Problem

I would like to improve the following code:

result = database.execute(script, fetch="0") # (6, 2016) for example
    month = str(result[0])
    year = str(result[1])
    if len(month) == 1:
        month = "0" + month
    return "%s/%s" % (month, year)


I'm feeling that my code is dumb, and could be more intelligent.

Python version 2.6.

Solution

You can use the datetime module:

import datetime as dt
result = (2, 2017)
date = dt.date(year=result[1], month=result[0], day=1)
date_str = date.strftime("%m/%Y")

Code Snippets

import datetime as dt
result = (2, 2017)
date = dt.date(year=result[1], month=result[0], day=1)
date_str = date.strftime("%m/%Y")

Context

StackExchange Code Review Q#152466, answer score: 9

Revisions (0)

No revisions yet.