Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
How to convert pandas offset to Python date?
In this article, we convert the pandas offset to date in python. When you subtract the pandas from a date object, you get a pandas Timestamp object. You can convert this object to a String format date or Date object(Standard Python date). Or you can use the timedelta object from the datetime library.
Example 1
In the following example code, we remove the offset of 10 days using to_offset("10D") from the pandas pd.to_datetime(?2018-01-04?).
from pandas.tseries.frequencies import to_offset import pandas as pd dt = pd.to_datetime('2018-01-04') - to_offset("10D") print(type(dt)) print(dt)
Output
The output of the above code is as follows.
<class 'pandas._libs.tslibs.timestamps.Timestamp'> 2017-12-25 00:00:00
In the above output, we can observe that the ?dt? variable is a string. To convert this string to a given format, you can use the strftime. And to convert this string to a date object, you can use the date() function.
Example 2
In the following example code, we convert the string ?2017-12-25 00:00:00? to ?yy-mm-dd? format by using the strftime() method. And to convert this string to a date object we use the date() function.
from pandas.tseries.frequencies import to_offset import pandas as pd dt = pd.to_datetime('2018-01-04') - to_offset("10D") print(dt.strftime('%Y-%m-%d')) print(dt.date()) print(type(dt.date()))
Output
The following is the output of the above code;
2017-12-25 2017-12-25 <class 'datetime.date'>
Example 3
Following is the example of converting pandas Offset to python date using pandas delta ?
from pandas.tseries.frequencies import to_offset import pandas as pd dt = pd.to_datetime('2018-01-04') - pd.Timedelta('10D') print(dt.strftime('%Y-%m-%d')) print(dt.date()) print(type(dt.date()))
Output
2017-12-25 2017-12-25
Example 4
Instead of Timedelta() we can also use to_timedelta() ?
from pandas.tseries.frequencies import to_offset import pandas as pd dt = pd.to_datetime('2022-09-10') - pd.to_timedelta('10D') print(dt.date())
Output
2022-08-31
