简体   繁体   中英

How to perform arithmetic operation on a date in Python?

I have a date column in csv file say Date having dates in this format 04/21/2013 and I have one more column Next_Day . In Next_Day column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013 as date then I want 04/22/2013 in Next_Day column.

We can use +1 in excel but I don't know how to perform this in Python.

Please help me in resolving this.

Using datetime.timedelta

>>> import datetime
>>> s = '04/21/2013'
>>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1)
>>> print(d.strftime('%m/%d/%Y'))
04/22/2013

Same answer as a one-liner. Prints 1 day 1 hour & 30 minutes ago from now:

python -c 'import datetime;print(datetime.datetime.now() - datetime.timedelta(days=1,hours=1,minutes=30))'

2022-02-08 13:11:06.304608

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM