Showing posts with label Date. Show all posts
Showing posts with label Date. Show all posts

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)

Python Date and Time

This is what we can do with the datetime and time modules 

in Python.


# import modules for the time and datetime

import time
import datetime


# working with the date and time 

print "Time in seconds since the epoch: %s" %time.time()
print "Current date and time: " , datetime.datetime.now()
print "Or like this: " ,datetime.datetime.now().strftime("%y-%m-%d-%H-%M")
print "Current year: ", datetime.date.today().strftime("%Y")
print "Month of year: ", datetime.date.today().strftime("%B")
print "Week number of the year: ", datetime.date.today().strftime("%W")
print "Weekday of the week: ", datetime.date.today().strftime("%w")
print "Day of year: ", datetime.date.today().strftime("%j")
print "Day of the month : ", datetime.date.today().strftime("%d")
print "Day of week: ", datetime.date.today().strftime("%A")


# That will print out something like this:

Time in seconds since the epoch: 1349271346.46
Current date and time: 2012-10-03 15:35:46.461491
Or like this: 12-10-03-15-35
Current year: 2012
Month of year: October
Week number of the year: 40
Weekday of the week: 3
Day of year: 277
Day of the month : 03
Day of week: Wednesday