How to move the date in Python – Snippet code

Dear All,

To move the date in python the following code may help.

Using this function we can move the days in both past date and future date by specifying the no of movedays with -ve/+ve sign accordingly.

</pre>
import datetime

def move_days(year,month,day,movedays):

'''
move_days : To move the day both direction and get the moved date yyyymmdd format

Condition :
passing year,month,day,movedays should be integer type.

Inputs:
movedays is an integer to move the date. It it is negative, then we should get the previous date with interval of the no of days [i.e. movedays ]

Outputs:
It should return the string type of the date formate like yyyymmdd

Usage:

example:
move_days(2011,04,03,200) returns '20111020'

move_days(2011,04,03,-200) returns '20100915'

Written by: Arulalan.T

Date: 03.04.2011

'''

if not (isinstance(year,int) and isinstance(month,int) and isinstance(day,int) and isinstance(movedays,int) ):

raise ValueError, ' year, month, day, movedays should be integer type '

daychanges = datetime.date(year,month,day) + datetime.timedelta(days = movedays)
daychanges = daychanges.timetuple()

year = str(daychanges[0])
month = str(daychanges[1])

if len(month) == 1 : month = '0' + month
day = str(daychanges[2])
if len(day) == 1 : day = '0' + day

return year + month + day

🙂 What I am learning here is, how to do coding and documentation in well good manner by myself 🙂

Advertisements

About arulalant

Currently working as "Project Scientist – C" in National Centre for Medium Range Weather Forecasting (NCMRWF), MoES, Noida, India
This entry was posted in Python and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s