Reputation: 287
I have this:
now = datetime.datetime.now()
year = now.year
month = now.month
num_days = calendar.monthrange(year, month)[1]
days = [datetime.date(year, month, day) for day in range(1, num_days + 1)] # return all the days of the current month
And it's return every days like this:
[datetime.date(2021, 8, 1),
datetime.date(2021, 8, 2),
datetime.date(2021, 8, 3),
.
.
.
datetime.date(2021, 8, 26),
datetime.date(2021, 8, 27),
datetime.date(2021, 8, 28),
datetime.date(2021, 8, 29),
datetime.date(2021, 8, 30),
datetime.date(2021, 8, 31)]
How can i get that days in normal format.
For example: 2021-08-01
Upvotes: 0
Views: 513
Reputation: 179
import calendar
import datetime
now = datetime.datetime.now()
year = now.year
month = now.month
num_days = calendar.monthrange(year, month)[1]
days = [datetime.date(year, month, day).strftime("%Y-%m-%d") for day in range(1, num_days + 1)]
print(days)
Use strftime function to convert datetime object to string in specified format
Upvotes: 2
Reputation: 18126
Convert your datetime objects to str
(as "YYYY-MM-DD" is the default format) or use .strftime()
:
import calendar, datetime
now = datetime.datetime.now()
year = now.year
month = now.month
num_days = calendar.monthrange(year, month)[1]
days = [
str(datetime.date(year, month, day)) for day in range(1, num_days + 1)
] # return all the days of the current month
print(days)
Out:
['2021-08-01', '2021-08-02', '2021-08-03', '2021-08-04', '2021-08-05', '2021-08-06', '2021-08-07', '2021-08-08', '2021-08-09', '2021-08-10', '2021-08-11', '2021-08-12', '2021-08-13', '2021-08-14', '2021-08-15', '2021-08-16', '2021-08-17', '2021-08-18', '2021-08-19', '2021-08-20', '2021-08-21', '2021-08-22', '2021-08-23', '2021-08-24', '2021-08-25', '2021-08-26', '2021-08-27', '2021-08-28', '2021-08-29', '2021-08-30', '2021-08-31']
Upvotes: 1