I want to print all dates of current month like this
2019-06-1
2019-06-2
2019-06-3
2019-06-4
2019-06-5
...
2019-06-28
2019-06-29
2019-06-30
How can I do it in python?
In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date class. Create an object of the date class. Call the today( ) function of date class to fetch todays date.
import pandas from datetime import datetime, timedelta startDate = datetime(2022, 6, 1) endDate = datetime(2022, 6, 10) # Getting List of Days using pandas datesRange = pandas. date_range(startDate,endDate-timedelta(days=1),freq='d') print(datesRange);
You can use datetime
:
from datetime import date, timedelta
d1 = date(2019, 6, 1)
d2 = date(2019, 6, 30)
delta = d2 - d1
for i in range(delta.days + 1):
print(d1 + timedelta(days=i))
Refining the code and making it independent of user specification:
from datetime import date, timedelta, datetime
import calendar
def all_dates_current_month():
month = datetime.now().month
year = datetime.now().year
number_of_days = calendar.monthrange(year, month)[1]
first_date = date(year, month, 1)
last_date = date(year, month, number_of_days)
delta = last_date - first_date
return [(first_date + timedelta(days=i)).strftime('%Y-%m-%d') for i in range(delta.days + 1)]
all_dates_current_month()
and you get:
['2019-06-01',
'2019-06-02',
'2019-06-03',
'2019-06-04',
'2019-06-05',
'2019-06-06',
'2019-06-07',
'2019-06-08',
'2019-06-09',
'2019-06-10',
'2019-06-11',
'2019-06-12',
'2019-06-13',
'2019-06-14',
'2019-06-15',
'2019-06-16',
'2019-06-17',
'2019-06-18',
'2019-06-19',
'2019-06-20',
'2019-06-21',
'2019-06-22',
'2019-06-23',
'2019-06-24',
'2019-06-25',
'2019-06-26',
'2019-06-27',
'2019-06-28',
'2019-06-29',
'2019-06-30']
calendar.monthrange
will tell you how many days that month has (considering leap years, etc). From there, you'll need a bunch of scaffolding to create the range:
from calendar import monthrange
def allDays(y, m):
return ['{:04d}-{:02d}-{:02d}'.format(y, m, d) for d in range(1, monthrange(y, m)[1] + 1)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With