程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

A python script for calculating time (the last day of the first day of a month / the last day of the first day of last week, etc.)

編輯:Python

Because in the previous automation work, almost every script has to be run at the time node , Like the first day of the week , The first and last day of each month, etc . This involves the calculation of time , But there is no ready-made package , You can only write one by yourself (╯‵□′)╯︵┻━┻.

Use cases

This script contains the time nodes used by general automated reports .

Time node Function method today (struct_time Format )today(today_s) yesterday yesterdayn Month ago, / A few months later month()n Month ago, / The first day of the following month month_start()n Month ago, / The last day of the following month month_end() First day of last week last_week_start() Last day of last week last_week_end() This week is the week of the year weeknum Today is the day of the week wday Today is the day of the month mday Today is the day of the year yday Days of the month mranges
day = Sometime(timestr="2019-04-25") # Specify the base date 
print(day.today)
print(day.yesterday)
print(day.month(n_mon=2)) # 2 A few months later 
print(day.month_start(n_mon=5)) # 5 Months later, the first day of the month 
print(day.month_end(n_mon=-6)) # 6 The first day of the month months ago 
print(day.last_week_start())
print(day.last_week_end())
print(day.today_s)
2019-04-25 00:00:00
2019-04-24
6
2019-09-01
2018-10-31
2019-04-15
2019-04-21
time.struct_time(tm_year=2019, tm_mon=4, tm_mday=25, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=115, tm_isdst=-1)
day1 = Sometime(n=2) # utilize n To specify the date , Positive numbers are the future , Negative numbers are the past 
print(day1.today)
print(day1.year)
print(day1.yday)
print(day1.mday)
print(day1.wday)
print(day1.weeknum)
print(day1.mranges)
2019-04-28
2019
118
28
6
17
30

Source code

import time
import datetime
import calendar
class Sometime:
def __init__(self, timestr=None, n=None):
""" Custom start date , Then calculate from the start date : Date of the day , Yesterday date , Start and end date of last month , Last week's start and end date , This week is the week of the year , Today is the day of the week Parameter setting : according to "2019-01-01" Fill in the form of n: int,n=0 Today , - n < 0 when ,1 Equal to yesterday ,2 Equal to the day before yesterday , And so on - n > 0 when ,-1 Tomorrow ,-2 The day after tomorrow , And so on ** Two parameters cannot exist at the same time !!!** """
if timestr is None:
if n is None:
time_str = datetime.date.today()
else:
time_str = (datetime.date.today() - datetime.timedelta(days=-n))
else:
if n is None:
time_str = datetime.datetime.strptime(timestr, "%Y-%m-%d")
else:
time_str = datetime.datetime.strptime(timestr, "%Y-%m-%d")
print(" Parameters timestr and n Can't be used at the same time !!!, Otherwise, it is used by default timestr Parameters ")
self.today = time_str
self.today_s = time_str.timetuple() # Output today's struct_time Format 
self.yesterday = (self.today - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
self.year = self.today_s.tm_year # This year's year 
self.mday = self.today_s.tm_mday # Today is the day of the month 
self.yday = self.today_s.tm_yday # Today is the day of the year 
self.wday = self.today_s.tm_wday # Today is the day of the week 
self.weeknum = self.today.isocalendar()[1] # This week is the week of the year 
self.mranges = calendar.monthrange(self.today_s.tm_year,
self.today_s.tm_mon)[1] # Days of the month 
def month(self, n_mon=0):
""" Calculation : n Month ago, ( When n When it's a negative number ) or n After month ( When n It's a positive number ) What month is it ** Default n=0 Return to the current month ** """
k = (self.today_s.tm_mon + n_mon) % 12
if n_mon == 0:
result = self.today_s.tm_mon
else:
result = 12 if k == 0 else k
return result
def month_start(self, n_mon=0):
""" Calculation : n Month ago, ( When n When it's a negative number ) or n After month ( When n It's a positive number ) The first day of the month ** Default n=0 Returns the first day of the current month ** """
month_l = self.month(n_mon=n_mon)
y = (self.today_s.tm_mon + n_mon) / 12
y1 = (self.today_s.tm_mon + n_mon) // 12
if y > 0:
if month_l == 12: # When the month is 12 The month is ahead of the year +1 The situation of 
year_l = self.year + y1 - 1
else:
year_l = self.year if y1 == 0 else self.year + y1
else:
year_l = self.year -1 if y1 == 0 else self.year + y1
result = datetime.date(
year=year_l,
month=month_l,
day=1).strftime('%Y-%m-%d')
return result
def month_end(self,n_mon=0):
""" Calculation : n Month ago, ( When n When it's a negative number ) or n After month ( When n It's a positive number ) The last day of the month ** Default n=0 Returns the last day of the current month ** """
month_l = self.month(n_mon=n_mon)
y = (self.today_s.tm_mon + n_mon) / 12
y1 = (self.today_s.tm_mon + n_mon) // 12
if y > 0:
if month_l == 12: # When the month is 12 The month is ahead of the year +1 The situation of 
year_l = self.year + y1 -1
else:
year_l = self.year if y1==0 else self.year + y1
else:
year_l = self.year -1 if y1 == 0 else self.year + y1
mrange = calendar.monthrange(year_l, month_l)[1]
result = datetime.date(
year=year_l,
month=month_l,
day=mrange).strftime('%Y-%m-%d')
return result
def last_week_start(self):
""" Return to the first day of last week """
result = (
self.today -
datetime.timedelta(
days=self.today.weekday() +
7)).strftime("%Y-%m-%d")
return result
def last_week_end(self):
""" Return to the last day of last week """
result = (
self.today -
datetime.timedelta(
days=self.today.weekday() +
1)).strftime("%Y-%m-%d")
return result

By two designations “ today ” The way , You can calculate the relevant date based on any day . Very convenient .
If you have any problems during the use , You can contact me .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved