Andrew
Andrew

Reputation: 203

Python previous month with 2 digit

I want 04 as output in premonth . Can some one help on this? tried diff format and no luck.

enter code here
premonth = str(int(time.strftime('%m'))-1)

tried using python date of the previous month but due to strftime restriction I am not able to proceed.

Upvotes: 0

Views: 777

Answers (2)

paxdiablo
paxdiablo

Reputation: 882336

The following f-string will give you what you need, it also handles January correctly by using arithmetic manipulation to ensure 1 becomes 12:

f'{(int(time.strftime("%m")) + 10) % 12 + 1:02}'

Breaking that down, an f-string is a modern way to build strings from arbitrary expressions, in a way that keeps formatting and data together (unlike the old "string".format(item, item) and even older "string" % (item, item)).

Inside that f-string is a rather complex looking expression which is formatted with :02, meaning two places, zero-padded on left.

The expression is what correctly decrements your month with proper wrapping, as you can see from the following table:

+-------+-----+-----+----++-------+-----+-----+----+
| Value | +10 | %12 | +1 || Value | +10 | %12 | +1 |
+-------+-----+-----+----++-------+-----+-----+----+
|     1 |  11 |  11 | 12 ||     7 |  17 |   5 |  6 |
|     2 |  12 |   0 |  1 ||     8 |  18 |   6 |  7 |
|     3 |  13 |   1 |  2 ||     9 |  19 |   7 |  8 |
|     4 |  14 |   2 |  3 ||    10 |  20 |   8 |  9 |
|     5 |  15 |   3 |  4 ||    11 |  21 |   9 | 10 |
|     6 |  16 |   4 |  5 ||    12 |  22 |  10 | 11 |
+-------+-----+-----+----++-------+-----+-----+----+

and the following statement:

print(", ".join([f'{mm}->{(mm + 10) % 12 + 1:02}' for mm in range(1, 13)]))

which outputs:

1->12, 2->01, 3->02, 4->03, 5->04, 6->05, 7->06, 8->07, 9->08, 10->09, 11->10, 12->11

Upvotes: 1

techytushar
techytushar

Reputation: 803

Not the best way but this should work:

a = str(int(time.strftime('%m'))-1)
a = '0'+a if len(a)==1 else a 

Upvotes: 1

Related Questions