Start Date - End Date OF Previous (Day, Week, Month and Year)

Here you can find out how to search the start date and end date of the different period in python.

The required modules of python to work with datetime are as below :

import datetime
form datetime import timedelta, date
import time 
from pytz import timezone
import pytz


Fetching Dates:

#Day:

st_date = datetime.datetime.now(pytz.timezone(str(tz))).date() - datetime.timedelta(days=1)
ed_date = datetime.datetime.now(pytz.timezone(str(tz))).date() - datetime.timedelta(days=1)

#week

year_pre_week_detail = str(datetime.datetime.now(pytz.timezone(str(tz))).date().strftime("%Y")) + '-                          W' + str(int(datetime.datetime.now(pytz.timezone(str(tz))).date().strftime("%W")) - 2)

st_date = datetime.datetime.strptime(year_pre_week_detail + '-0', "%Y-W%W-%w").strftime('%Y-%m-%d')

ed_date = (datetime.datetime.strptime(str(st_date), "%Y-%m-%d") +  
                  datetime.timedelta(days=6)).strftime('%Y-%m-%d')

#Month 

ed_date = date.today().replace(day=1) - timedelta(days=1)
st_date = ed_date.replace(day=1)
         
#Year
 
st_date = date(date.today().year, 1, 1)
ed_date = date(date.today().year, 12, 31)

0 comments:

Post a Comment