How To Generate A Range Of Yyyymm Values?
I have two yyyymm values that will be input by a user: yyyymm_1 = '201406' yyyymm_2 = '201501' I want to be able to iterate through this range in increasing month order: for yyyy
Solution 1:
Here's another rather simple variant, without even using datetime
. Just split the date, calculate the 'total month', and iterate.
def to_month(yyyymm):
y, m = int(yyyymm[:4]), int(yyyymm[4:])
return y * 12 + m
def iter_months(start, end):
for month in range(to_month(start), to_month(end) + 1):
y, m = divmod(month-1, 12) # ugly fix to compensate
yield y, m + 1 # for 12 % 12 == 0
for y, m in iter_months('201406', '201501'):
print y, m
Output:
2014 6
2014 7
...
2014 12
2015 1
For output in the same yyyymm
format, use print("%d%02d" % (y, m))
.
Solution 2:
You can do this using the builtin datetime
module and the third party package dateutil
.
The code first converts your strings to datetime.datetime
objects using datetime.datetime.strptime
. It then uses the relativedelta
function from dateutil
to create a period of one month that can be added to your datetimes.
Within the while
loop you can either work with the datetime
objects directly, or construct the month and year as strings using strftime
, I've shown an example of both in print functions.
import datetime as dt
from dateutil.relativedelta import relativedelta
yyyymm_1 = '201406'
yyyymm_2 = '201501'
MONTH = relativedelta(months=+1)
fmt = '%Y%m'
date_1 = dt.datetime.strptime(yyyymm_1, fmt).date()
date_2 = dt.datetime.strptime(yyyymm_2, fmt).date()
d = date_1
while d <= date_2:
print(d)
print(d.strftime('%Y'), d.strftime('%m'))
d += MONTH
Post a Comment for "How To Generate A Range Of Yyyymm Values?"