What is the quickest way to increment date string YYYY-MM-DD in Python?
Pure Python
You can use the datetime
module, part of the standard library. There are 3 steps:
- Convert string to
datetime
object viastrptime
. - Add a day via
timedelta
. - Convert resulting
datetime
object back to string viastrftime
.
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
Pandas
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