In this blog we will look at how to extract date,month and year infromation from date string¶
In [2]:
import pandas as pd
import numpy as np
from datetime import datetime
from datetime import date
from datetime import timedelta
Step 1: Create date string¶
In [3]:
todays_date=date.today()
todays_date
Out[3]:
datetime.date(2022, 3, 25)
In [9]:
type(todays_date)
Out[9]:
datetime.date
Step 2: Get month¶
In [4]:
todays_date.month
Out[4]:
3
Step 3: Get month name¶
In [13]:
pd.to_datetime(todays_date).month_name()
Out[13]:
'March'
Step 4: Get year¶
In [14]:
todays_date.year
Out[14]:
2022
Step 5: Get date¶
In [16]:
todays_date.day
Out[16]:
25
Step 6: Add days to a date¶
In [18]:
date.today()
Out[18]:
datetime.date(2022, 3, 25)
In [21]:
# Add 10 days to todays date
days_added_to_today = date.today() + timedelta(days=10)
days_added_to_today
Out[21]:
datetime.date(2022, 4, 4)
Step 7: Subtract days from a date¶
In [22]:
date.today()
Out[22]:
datetime.date(2022, 3, 25)
In [23]:
# Subtract 5 days to todays date
date.today() - timedelta(days=5)
Out[23]:
datetime.date(2022, 3, 20)
Step 8: Subtract two dates and convert difference into days value¶
In [25]:
date1= date.today()
date1
Out[25]:
datetime.date(2022, 3, 25)
In [26]:
date2= date.today() + timedelta(days=10)
date2
Out[26]:
datetime.date(2022, 4, 4)
In [29]:
date_diff=date2 - date1
date_diff
Out[29]:
datetime.timedelta(days=10)
In [34]:
date_diff.days
Out[34]:
10
No comments:
Post a Comment