Python the first and last day of the month, etc.

python date manipulation

Import the package:

import calendar
import datetime
from datetime import timedelta

Get today's date:

#返回datetime格式:eg:2019-12-07 20:38:35.82816
now = datetime.datetime.now()

#返回datetime格式:eg:2019-12-07
now = datetime.datetime.now().date()
now = datetime.date.today()

Get yesterday's date:

yesterday = now - timedelta(days=1)

Get tomorrow's date:

tomorrow = now + timedelta(days=1)

Get the first and last day of the week:

this_week_start = now - timedelta(days=now.weekday())
this_week_end = now + timedelta(days=6-now.weekday())

Get the first and last day of the previous week:

last_week_start = now - timedelta(days=now.weekday()+7)
last_week_end = now - timedelta(days=now.weekday()+1)

Get the first and last day of the month:

this_month_start = datetime.datetime(now.year, now.month, 1)
this_month_end = datetime.datetime(now.year, now.month, calendar.monthrange(now.year, now.month)[1])

Note:
calendar.monthrange(year,month) is
passed in two values: one is the current year, the other is the current month.
Writing can be: calendar.monthrange(now.year,now.month)

Two integers are returned.
The first value is the day of the week of the first day of the month, and the corresponding number. 0-6==>0 (Monday) to 6 (Sunday) The
second value is the total number of days in the month.

Get the first and last day of the previous month:

last_month_end = this_month_start - timedelta(days=1) 
last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)

Get the first and last day of the season:

month = (now.month - 1) - (now.month - 1) % 3 + 1
this_quarter_start = datetime.datetime(now.year, month, 1)
this_quarter_end = datetime.datetime(now.year, month, calendar.monthrange(now.year, now.month)[1]) 

Get the first and last day of the previous season:

last_quarter_end = this_quarter_start - timedelta(days=1)
last_quarter_start = datetime.datetime(last_quarter_end.year, last_quarter_end.month - 2, 1)

Get the first and last day of the year:

this_year_start = datetime.datetime(now.year, 1, 1)
this_year_end = datetime.datetime(now.year + 1, 1, 1) - timedelta(days=1)

Get the first and last day of last year:

last_year_end = this_year_start - timedelta(days=1)
last_year_start = datetime.datetime(last_year_end.year, 1, 1) 

If you want to get the date format, add ".date" at the end.

Guess you like

Origin blog.csdn.net/weixin_42464956/article/details/108778388