Python method of calculating the first day of a month before and after a given point in time
- 2020-10-23 21:04:44
- OfStack
An example of this article describes Python's method for calculating the 1st day of a month before and after a given point in time. To share for your reference, the details are as follows:
How to obtain the first month and the second month of the time point of python? Although there are many tutorials online, I feel it is too miscellaneous and not easy to use. After a study, I decided to provide a method and idea.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
import calendar
time = datetime.date(2017, 7, 20) # Year, month, day
# For a month first 1 day
first_day = datetime.date(time.year, time.month, 1)
print u' The first month 1 day :' + str(first_day)
# Ask before 1 In the first months 1 day
# before 1 Months of the last 1 day
pre_month = first_day - datetime.timedelta(days = 1) #timedelta is 1 It's a nice function
print u' before 1 Months of the last 1 day :' + str(pre_month)
# before 1 In the first months 1 day
first_day_of_pre_month = datetime.date(pre_month.year, pre_month.month, 1)
print u' before 1 In the first months 1 day :' + str(first_day_of_pre_month)
# After o 1 In the first months 1 day
days_num = calendar.monthrange(first_day.year, first_day.month)[1] # To obtain 1 How many days are there in a month
first_day_of_next_month = first_day + datetime.timedelta(days = days_num) # The end of the month 1 Day just days_num-1 Can be
print u' after 1 In the first months 1 day :' + str(first_day_of_next_month)
The results are as follows
[
The 1st day of the month :2017-07-01
The last day of the previous month :2017-06-30
Day 1 of the previous month :2017-06-01
Day 1 of the following month :2017-08-01
PS: Here are a few more online tools for your reference:
Online days calculator:
http://tools.ofstack.com/jisuanqi/datejsq
In the day difference calculator:
http://tools.ofstack.com/jisuanqi/onlinedatejsq
Online date calculator/Difference day calculator:
http://tools.ofstack.com/jisuanqi/datecalc
Online Date/Day calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi
More about Python related topics: interested readers to view this site "Python date and time operating skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"
I hope this article has been helpful in Python programming.