HomeLanguagesGet Month from date in Pandas – Python

Get Month from date in Pandas – Python

Pandas has many inbuilt methods that can be used to extract the month from a given date that are being generated randomly using the random function or by using Timestamp function or that are transformed to date format using the to_datetimefunction. Let’s see few examples for better understanding.

Example 1




import pandas as pd
  
  
dti = pd.date_range('2020-07-01', periods = 4, freq ='M')
print(dti.month)


Output:

Int64Index([7, 8, 9, 10], dtype='int64')

Example 2




import pandas as pd
import numpy as np
import datetime
  
date1 = pd.Series(pd.date_range('2020-7-1 12:00:00', periods = 5))
df = pd.DataFrame(dict(date_given = date1))
  
df['month_of_date'] = df['date_given'].dt.month
df


Output:

pandas-datetime-1

Example 3




import pandas as pd
import datetime
import numpy as np
  
  
dates =['14 / 05 / 2017', '2017', '07 / 09 / 2017']
  
frame = pd.to_datetime(dates, dayfirst = True)
frame = pd.DataFrame([frame]).transpose()
frame['date']= frame
frame['month']= frame['date'].dt.month
frame.drop(0, axis = 1, inplace = True)
  
frame


Output:

pandas-datetime-2

RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32688 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
7057 POSTS0 COMMENTS
Nicole Veronica
12198 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12293 POSTS0 COMMENTS
Shaida Kate Naidoo
7182 POSTS0 COMMENTS
Ted Musemwa
7447 POSTS0 COMMENTS
Thapelo Manthata
7160 POSTS0 COMMENTS
Umr Jansen
7150 POSTS0 COMMENTS