We created one date timedelta64 column by using to_datetime(). Here is the output
NAME dt_start
0 Ravi 2020-01-31
1 Raju 2020-02-29
2 Alex 2019-02-28
We can add ( or subtract ) dates from above values by using keywords years, months, weeks, days, hours, minutes, seconds, microseconds, nanoseconds We can REPLACE part of the date object also.
NAME dt_start dt_end
0 Ravi 2020-01-31 2020-01-31 02:50:43
1 Raju 2020-02-29 2020-02-29 02:50:43
2 Alex 2019-02-28 2019-02-28 02:50:43
Similarly we can add microseconds and nanoseconds
Replace
In above code we have added ( or subtracted ) the date and time parts. We can replace the parts by using different set of keywords.
Note that year ( used above ) is not same as years.
year month day weekday
hour minute second microsecond nanosecond
We are updating the year part only ( not adding or subtracting )
tm=pd.Timestamp('now') # current timestamp
x=pd.offsets.DateOffset(years=1,months=2,days=3,\
hours=4,minutes=40,seconds=20)
print(tm+x)
Output
2022-08-07 14:48:00.151036
Using timedelta64 we can add or subtact date parts.
import pandas as pd
import numpy as np
tm=pd.Timestamp('now') # current timestamp
y=np.timedelta64(1,'M') # adding one month
z=np.timedelta64(1,'Y') # adding one year
print(tm+y+z)
Output
2022-07-05 02:35:38.978611
Practice this exercise to understand how to use date and time in Pandas DataFrame.
Exercise3 on Date and time