In this blog we will look at function which are used to handle dates in Python¶
Step 1: Importing Libraries¶
In [1]:
import pandas as pd
import numpy as np
Step 2: Creating Sample date¶
In [3]:
dt_val = "20 Jan 2022"
dt_val
Out[3]:
'20 Jan 2022'
In [7]:
# If we look at the data type, it is basically a string
type(dt_val)
Out[7]:
str
Step 3: Using data_time from Pandas to convert it into a date¶
In [13]:
dt_val_2 = pd.Series(dt_val)
dt_val_2
Out[13]:
0 20 Jan 2022 dtype: object
In [17]:
dt_val_3 = pd.to_datetime(dt_val_2)
dt_val_3
Out[17]:
0 2022-01-20 dtype: datetime64[ns]
Step 4: Other date strings that can be handled¶
In [18]:
other_val = pd.Series(['22/09/2020','22-09-2020','20200922','2020-09-22T13:25'])
other_val
Out[18]:
0 22/09/2020 1 22-09-2020 2 20200922 3 2020-09-22T13:25 dtype: object
All the date mentioned in the above series are object(basically text values).Lets convert them into date format using date_time function¶
In [21]:
other_val_dt=pd.to_datetime(other_val)
other_val_dt
Out[21]:
0 2020-09-22 00:00:00 1 2020-09-22 00:00:00 2 2020-09-22 00:00:00 3 2020-09-22 13:25:00 dtype: datetime64[ns]
No comments:
Post a Comment