- How to get all days in current month?
- 7 Answers 7
- Datetime current year and month in Python
- Python get month from date
- How do you get the month number from a datetime object in Python?
- Python get month from date
- Pandas get month number from datetime
- Python get year month number from date
- Pandas get year month number from datetime
- Related articles
- References
- Stephen Allwright Twitter
How to get all days in current month?
I want to get all datetime object of each day in the current month but I haven’t done yet. The result expected I wanted:
[datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), . datetime.date(2014, 1, 29), datetime.date(2014, 1, 30), datetime.date(2014, 1, 31)]
Do you want to know how many days there are in a month? Do you want a datetime object for each day of a month? Please clarify what exactly you’re looking for in more detail, and also show us what you’ve tried so far.
7 Answers 7
Here’s a solution with datetime and calendar :
>>> import datetime, calendar >>> year = 2014 >>> month = 1 >>> num_days = calendar.monthrange(year, month)[1] >>> days = [datetime.date(year, month, day) for day in range(1, num_days+1)] >>> days [datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5), datetime.date(2014, 1, 6), datetime.date(2014, 1, 7), datetime.date(2014, 1, 8), datetime.date(2014, 1, 9), datetime.date(2014, 1, 10), datetime.date(2014, 1, 11), datetime.date(2014, 1, 12), datetime.date(2014, 1, 13), datetime.date(2014, 1, 14), datetime.date(2014, 1, 15), datetime.date(2014, 1, 16), datetime.date(2014, 1, 17), datetime.date(2014, 1, 18), datetime.date(2014, 1, 19), datetime.date(2014, 1, 20), datetime.date(2014, 1, 21), datetime.date(2014, 1, 22), datetime.date(2014, 1, 23), datetime.date(2014, 1, 24), datetime.date(2014, 1, 25), datetime.date(2014, 1, 26), datetime.date(2014, 1, 27), datetime.date(2014, 1, 28), datetime.date(2014, 1, 29), datetime.date(2014, 1, 30), datetime.date(2014, 1, 31)]
import calendar print calendar.monthcalendar(2013, 4) [[1, 2, 3, 4, 5, 6, 7], [8, 9, 10, 11, 12, 13, 14], [15, 16, 17, 18, 19, 20, 21], [22, 23, 24, 25, 26, 27, 28], [29, 30, 0, 0, 0, 0, 0]]
There are several methods, but with calendar.monthrange , you can get a tuple (first_weekday, nb_days) :
>>> from calendar import monthrange >>> monthrange(2014, 2) (5, 28) >>> a = monthrange(2014, 2) >>> range(1, a[1]+1) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28] >>> [datetime.date(2014, 2, day) for day in range(1, a[1]+1)] [datetime.date(2014, 1, 1), datetime.date(2014, 1, 2), datetime.date(2014, 1, 3), datetime.date(2014, 1, 4), datetime.date(2014, 1, 5), datetime.date(2014, 1, 6), datetime.date(2014, 1, 7), datetime.date(2014, 1, 8), datetime.date(2014, 1, 9), datetime.date(2014, 1, 10), datetime.date(2014, 1, 11), datetime.date(2014, 1, 12), datetime.date(2014, 1, 13), datetime.date(2014, 1, 14), datetime.date(2014, 1, 15), datetime.date(2014, 1, 16), datetime.date(2014, 1, 17), datetime.date(2014, 1, 18), datetime.date(2014, 1, 19), datetime.date(2014, 1, 20), datetime.date(2014, 1, 21), datetime.date(2014, 1, 22), datetime.date(2014, 1, 23), datetime.date(2014, 1, 24), datetime.date(2014, 1, 25), datetime.date(2014, 1, 26), datetime.date(2014, 1, 27), datetime.date(2014, 1, 28), datetime.date(2014, 1, 29), datetime.date(2014, 1, 30), datetime.date(2014, 1, 31)]
With a function to make it cleaner:
from calendar import monthrange import datetime def get_datetime_range(year, month): nb_days = monthrange(year, month)[1] return [datetime.date(year, month, day) for day in range(1, nb_days+1)] print get_datetime_range(2014, 2) # usage example
Datetime current year and month in Python
Works, thanks! Is there an advantage over .now() rather than .today() as used in other answers? The now() function is shorter, it’s more commonly used. but is there any reason to use one over the other when all one wants to know is what year it is?
@Cadoiz — The datetime package has a few submodules — the date submodule ( from datetime import date ) which just deals with dates, the time submodule which deals with times, and the unfortunately-named datetime submodule which does both. There’s also timedelta and tzinfo in there. One could just import datetime to get the whole package with all the submodules, but then method calls would look like datetime.datetime.now() or datetime.date.today() . Typically, it’s nicer for several reasons to import just the components you need.
This answer suffers from a potential issue if the time is almost exactly midnight. One variable could contain a value from one day and another could contain one from the next day if the day rolls over during the milliseconds between statements. Save the now() value in a variable then extract the parts from that variables values. This will produce a consistent result. See @llogiq ‘s answer.
from datetime import datetime today = datetime.today() datem = datetime(today.year, today.month, 1)
I assume you want the first of the month.
@jpobst I’m using Python 3.8.1 & datetime-4.3 zope.interface-4.7.1, and the above code (with import datetime) works for me. If I write from datetime import datetime, it throws me AttributeError: type object ‘datetime.datetime’ has no attribute ‘datetime’
from datetime import datetime current_month = datetime.now().strftime('%m') // 02 //This is 0 padded current_month_text = datetime.now().strftime('%h') // Feb current_month_text = datetime.now().strftime('%B') // February current_day = datetime.now().strftime('%d') // 23 //This is also padded current_day_text = datetime.now().strftime('%a') // Fri current_day_full_text = datetime.now().strftime('%A') // Friday current_weekday_day_of_today = datetime.now().strftime('%w') //5 Where 0 is Sunday and 6 is Saturday. current_year_full = datetime.now().strftime('%Y') // 2018 current_year_short = datetime.now().strftime('%y') // 18 without century current_second= datetime.now().strftime('%S') //53 current_minute = datetime.now().strftime('%M') //38 current_hour = datetime.now().strftime('%H') //16 like 4pm current_hour = datetime.now().strftime('%I') // 04 pm current_hour_am_pm = datetime.now().strftime('%p') // 4 pm current_microseconds = datetime.now().strftime('%f') // 623596 Rarely we need. current_timzone = datetime.now().strftime('%Z') // UTC, EST, CST etc. (empty string if the object is naive).
The above things are useful for any date parsing, not only now or today. It can be useful for any date parsing.
e.g. my_date = "23-02-2018 00:00:00" datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S+00:00') datetime.strptime(str(my_date),'%d-%m-%Y %H:%M:%S').strftime('%m')
Python get month from date
Being able to get the month number, or year month number, from a DateTime object in Python can be extremely helpful for feature engineering. In this post, I will walk through how to do this simply in multiple variations.
How do you get the month number from a datetime object in Python?
In order to get the month number from a datetime object in Python, all you need to do is use the .month method. This is a much simpler operation than getting, for example, the week number as there aren’t multiple interpretations of the aggregation.
Python get month from date
Getting the month number from a datetime object in Python requires very little code, here is the most simple example of implementing it.
import datetime date = datetime.date(2022, 9, 1) month_number = date.month print(date) print(f"Month number is: ") """ Output: 2022-09-01 Month number is: 9 """
Pandas get month number from datetime
If you’re using Pandas as a way to store your data then you can easily get the month number from a datetime column by using the .dt.month method.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("30/8/2022 09:00:00", periods=4, freq="D")) df["month_number"] = df["datetime"].dt.month """ Output: datetime month_number 0 2022-08-30 09:00:00 8 1 2022-08-31 09:00:00 8 2 2022-09-01 09:00:00 9 3 2022-09-02 09:00:00 9 """
Python get year month number from date
If you have a dataset that spans multiple years then you may want to return a combination of year and month to make it unique. Here is how this can be done in Python using strftime
import datetime date = datetime.date(2022, 9, 1) year_month = date.strftime('%Y-%m') print(date) print(f"Year month combination: ") """ Output: 2022-09-01 Year month combination: 2022-09 """
Pandas get year month number from datetime
It’s also possible to calculate this unique year-month combination for a Pandas dataframe using the same approach.
import pandas as pd df = pd.DataFrame( columns=["datetime"], data=pd.date_range("30/8/2022 09:00:00", periods=4, freq="D")) df["year_month"] = df["datetime"].dt.strftime('%Y-%m') """ Output: datetime year_month 0 2022-08-30 09:00:00 2022-08 1 2022-08-31 09:00:00 2022-08 2 2022-09-01 09:00:00 2022-09 3 2022-09-02 09:00:00 2022-09 """
Related articles
References
Stephen Allwright Twitter
I’m a Data Scientist currently working for Oda, an online grocery retailer, in Oslo, Norway. These posts are my way of sharing some of the tips and tricks I’ve picked up along the way.