I want to print out a date for a certain period with Python.
For example, from 20160901 to 20161031.
However, simply take the range and
date1 = int('20160901')
date2 = int('20161032')
for x in range(date1, date2):
print x
If you use it like this, you can use it until September 30th, but
20160901
...
20160930
20160931
20160932
...
20160999
20161000
20161001
...
20161031
This is how it's printed.
What I want is 20161001 to be printed after 201660930.
In the end, the above method includes all the corresponding periods, so the results are printed, but there is a problem with efficiency due to a lot of garbage. When I saved it as a time type as datetime, there was a problem using the range (int type, int type).
I can't think of a proper way, so I'm asking you a question.
python
calendar.monthrange(year, month)
returns what day of the month is the 1st of the month (Monday is 0) and how long the month is.
import calendar
print calendar.monthrange(2016,10)
# Execution result value (5, 31)
With the time
module
Using the return value above, I think you can fully implement the function you want
It's been two years since I asked this question, but I happened to see this article and I think there's a better way to help others, so I'm answering it additionally.
It is simple to use date_range()
in pandas
.
import pandas
dt_index = pandas.date_range(start='20160901', end='20161031')
# # pandas.date_range(start='20160901', end='20161031',freq='W-MON')
# If you do, extract only Mondays during the period.
# # type(dt_index) => DatetimeIndex
# # DatetimeIndex => list(str)
dt_list = dt_index.strftime("%Y%m%d").tolist()
for i in dt_list:
print(i)
I also used the answer that Kim Sun-woo left. It's my first time using calendar library.
And if I were to leave one more as a self-answer,
import datetime
today = datetime.date.today()
print today
today = today + datetime.timedelta(+10)
print today
If you write like this
2016-10-23 2016-11-02
This is how it's printed. It's calculated on its own. You can put a number of values such as date, time, millisecond, and so on You were able to adjust the date value by +/-.
© 2024 OneMinuteCode. All rights reserved.