DateTime functions in Python

Some useful date/time functions in Python:

import time
import datetime
from time import gmtime, strftime
from datetime import datetime, timedelta, date
from dateutil.relativedelta import relativedelta

def validateApiDate(apiDate):
    '''
    Validates non-standard date string format
    ''' 
    try:
        dt = datetime.datetime.strptime(apiDate, '%Y%m%d').date()
        #print type(dt)
        dt = datetime.datetime.strftime(dt, '%Y-%m-%d')
        print dt
    except ValueError:
        return False

def addDaysToCurrentDate(numDays):
    '''
    Add days to current date
    '''
    d = date.today() + timedelta(days=numDays)
    return int(time.mktime(datetime.datetime.strptime(str(d), '%Y-%m-%d').timetuple()))

def getTimeDelta(numDays):
    '''
    Add days to current date
    '''
    d = date.today() + timedelta(days=numDays)
    return d.timetuple()

def validatePastDate(d):
    '''
    Validate if the date is a past date
    '''
    dt = datetime.datetime.strptime(d, '%Y%m%d').date()
    #print type(dt)
    today = date.today()
    #print type(today)
    diff = (dt-today).days
    #print type(diff)
    print diff

def first_of_last_month():
    '''
    Get 1st of last month. Works with python 2.7 and higher
    '''
    one_month_ago = date.today() + relativedelta(months=-1)
    first_day_last_month = (one_month_ago.year, one_month_ago.month, 1)
    return first_day_last_month

def first_of_last_month_py26():
    '''
    Get 1st of last month. Works with python 2.6 or older
    '''
    first_day_of_current_month = date.today().replace(day=1)
    last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
    first_date_of_last_month = last_day_of_previous_month.replace(day=1)
    return first_date_of_last_month

def yesterdayDateTime():
    '''
    Get date and time from 24 hours ago
    '''
    yesterdayDateTime = datetime.today() - timedelta(days = 1)
    return yesterdayDateTime.strftime('%m-%d-%Y %H:%M:%S')

def dateTimeToDate(dt):
    '''
    Convert datetime to date (strip off time)
    '''
    return dt.date()

def validate_last_day_of_next_month():
        '''
        Function to parse through all days in year and display the last day of next month
        '''
	today = date.today()
	days_in_month = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
	for mon in range (1,13):
		for day in range (1,days_in_month[mon]+1):
			today = date(2017,mon,day)
			if today.year % 12 == 0:
				days_in_month[2] = 29
			else:
				days_in_month[2] = 28
			current_month = today.month
			current_year = today.year
			next_month = current_month + 1 if current_month < 12 else 1
			next_months_year = current_year + 1 if current_month == 12 else current_year
			next_month_last_day = date(next_months_year, next_month, days_in_month[next_month])
			print '%s : %s' % (next_month_last_day, today)
		print "\n\n"

def last_day_of_next_month(today=date.today()):
	days_in_month = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
	if today.year % 12 == 0:
		days_in_month[2] = 29
	current_month = today.month
	current_year = today.year
	next_month = current_month + 1 if current_month < 12 else 1
	next_months_year = current_year + 1 if current_month == 12 else current_year
	next_month_last_day = date(next_months_year, next_month, days_in_month[next_month])
	return next_month_last_day

strptime translates to parse (convert) string to datetime object.
strftime translates to create formatted string for given time/date/datetime object according to specified format.

Advertisements

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