In Pandas, I am using dates with string format YYYY-MM-DD
What is the quickest way to increment the date with the result in YYYY-MM-DD
format?
d1 = '2018-02-10'
I want to increment it by 1 and get the result back as a string:
d1_inc = '2018-02-11'
yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime.
strptime is short for "parse time" where strftime is for "formatting time". That is, strptime is the opposite of strftime though they use, conveniently, the same formatting specification.
Use datetime. strftime(format) to convert a datetime object into a string as per the corresponding format . The format codes are standard directives for mentioning in which format you want to represent datetime. For example, the %d-%m-%Y %H:%M:%S codes convert date to dd-mm-yyyy hh:mm:ss format.
You can use the datetime
module, part of the standard library. There are 3 steps:
datetime
object via strptime
.timedelta
.datetime
object back to string via strftime
.Here's a demo:
from datetime import datetime, timedelta
x = '2017-05-15'
res = (datetime.strptime(x, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
The equivalent steps can be performed using 3rd party Pandas:
x = '2017-05-15'
# choose some combination of below methods
res = (pd.Timestamp(x) + pd.DateOffset(days=1)).strftime('%Y-%m-%d')
res = (pd.to_datetime(x) + pd.Timedelta('1 day')).strftime('%Y-%m-%d')
print(res)
# 2017-05-16
Using pd.to_datetime
, pd.TimeDelta
and strftime
:
fmt = '%Y-%m-%d'
(pd.to_datetime(<your series or column>, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
Example
df = pd.DataFrame({'date': ['2017-04-02', '2017-04-23']})
fmt = '%Y-%m-%d'
>>> (pd.to_datetime(df.date, format=fmt) + pd.Timedelta('1 days')).dt.strftime(date_format=fmt)
0 2017-04-03
1 2017-04-24
Name: date, dtype: object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With