Python - Extracting the first day of month of a datetime type column in pandas

In this article, we are going to learn how to extract the first day of the month of a DateTime type column in pandas?
Submitted by Pranit Sharma, on August 29, 2022

Problem statement

Suppose, we have a DataFrame with a column containing DateTime values, we are going to extract the date part and then we will extract the first day of the month from this date value. The date time value in this column can only be set with the help of the datetime library.

Python Datetime Library

Datetime is a library in Python which is a collection of date and time. Inside Datetime, we can access date and time in any format, but usually date is present in the format of "yy-mm-dd" and the time is present in the format of "HH:MM:SS".

Here,

  • yy means year
  • mm means month
  • dd means day
  • HH means hours
  • MM means minutes
  • SS means seconds

Extracting the first day of month of a datetime type column

For this purpose, use the following code statement with the specified column name, here the column name is "Datetime".

(df['Datetime'].dt.floor('d') + pd.offsets.MonthEnd(0) - pd.offsets.MonthBegin(1))

Let us understand with the help of an example,

Python program to extract the first day of month of a datetime type column in pandas

# Importing pandas package
import pandas as pd

# Creating a dictionary
d = {
    'Datetime':[
        '2012-07-21 14:05:21',
        '2017-12-05 05:07:30',
        '2011-08-28 17:08:51',
        '2014-12-04 17:07:30',
        '2019-03-03 18:32:56'
        ]
}

# Creating DataFrame
df=pd.DataFrame(d)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

# Converting values of DataFrame to datetime
df['Datetime'] = pd.to_datetime(df['Datetime'])

# Extracting first day of month from date
df['month'] = (df['Datetime'].dt.floor('d') + pd.offsets.MonthEnd(0) - pd.offsets.MonthBegin(1))

# Display modified DataFrame
print("Modified DataFrame:\n",df)

Output

The output of the above program is:

Example: Extracting the first day of month of a datetime type column

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.