converting string 'yyyy-mm-dd' into datetime python

Udaya Tenneti picture Udaya Tenneti · Apr 21, 2015 · Viewed 95.2k times · Source

I have a raw input from the user such as "2015-01-30"...for the query I am using, the date has to be inputed as a string as such "yyyy-mm-dd".

I would like to increment the date by 1 month at end of my loop s.t "2015-01-30" becomes "2015-02-27" (ideally the last business day of the next month). I was hoping someone could help me; I am using PYTHON, the reason I want to convert to datetime is I found a function to add 1 month.

Ideally my two questions to be answered are (in Python):

1) how to convert string "yyyy-mm-dd" into a python datetime and convert back into string after applying a timedelta function

2) AND/or how to add 1 month to string "yyyy-mm-dd"

Answer

Tenzin picture Tenzin · Apr 21, 2015

Maybe these examples will help you get an idea:

from dateutil.relativedelta import relativedelta
import datetime

date1 = datetime.datetime.strptime("2015-01-30", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)

today = datetime.date.today()
print(today)
addMonths = relativedelta(months=3)
future = today + addMonths
print(future) 

If you import datetime it will give you more options in managing date and time variables.
In my example above I have some example code that will show you how it works.

It is also very usefull if you would for example would like to add a x number of days, months or years to a certain date.

Edit: To answer you question below this post I would suggest you to look at "calendar"

For example:

import calendar 
january2012 = calendar.monthrange(2002,1)
print(january2012)
february2008 = calendar.monthrange(2008,2)
print(february2008)

This return you the first workday of the month, and the number of days of the month.
With that you can calculate what was the last workday of the month.
Here is more information about it: Link
Also have a loook here, looks what you might could use: Link