Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the quickest way to increment date string YYYY-MM-DD in Python?

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'
like image 729
afshin Avatar asked May 15 '18 10:05

afshin


People also ask

How do I change date format from YYYY MM DD in Python?

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.

What is the difference between Strftime and Strptime in Python?

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.

How do you change the date format of a string in Python?

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.


2 Answers

Pure Python

You can use the datetime module, part of the standard library. There are 3 steps:

  1. Convert string to datetime object via strptime.
  2. Add a day via timedelta.
  3. Convert resulting 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

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
like image 148
jpp Avatar answered Sep 28 '22 04:09

jpp


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
like image 43
Ami Tavory Avatar answered Sep 28 '22 04:09

Ami Tavory