[英]extract last day and first day from month in python
i am new in python ,i have a string of this format 我是python的新手,我有此格式的字符串
Ex. 'Mar-00'
how could i calculate first day and last day from this month. 我如何计算本月的第一天和最后一天。
OUTPUT : 输出:
first day : 01-Mar-00
last day : 31-Mar-00
ex : 'Feb-17' 例如:“ Feb-17”
first day : 01-Feb-17
last day : 28-Feb-17
you can use calendar.monthrange(year, month)[1]
to get the number of days in a given month+year. 您可以使用calendar.monthrange(year, month)[1]
来获取给定月份+年中的天数。
the first is alway 01, and last is the value of calendar.monthrange(year, month)[1]
第一个始终为01,最后一个为calendar.monthrange(year, month)[1]
try this, let me know if it works: 试试这个,让我知道它是否有效:
import calendar
month_abbr_to_num = {v: k for k,v in enumerate(calendar.month_abbr)}
month_abbr, year_2_digit = input("please enter month, e.g. Mar-00: ").split('-')
month = month_abbr_to_num[month_abbr]
year = int('20'+year_2_digit)
days_in_month = calendar.monthrange(year,month)[1]
print("first day : {:02d}-{}-{}".format(1, month_abbr, year_2_digit))
print("last day : {:02d}-{}-{}".format(days_in_month, month_abbr, year_2_digit))
EDIT: 编辑:
following your comment on original question, here it is in the form of a function that returns both as datetime
objects: 在您对原始问题发表评论之后,此处以函数形式返回两个datetime
对象:
import calendar
import datetime
month_abbr_to_num = {v: k for k,v in enumerate(calendar.month_abbr)}
def get_first_and_last_day(user_input):
month_abbr, year_2_digit = user_input.split('-')
month = month_abbr_to_num[month_abbr]
year = int('20' + year_2_digit)
days_in_month = calendar.monthrange(year, month)[1]
first_day = datetime.datetime(year, month, 1)
last_day = datetime.datetime(year, month, days_in_month)
return first_day, last_day
first, last = get_first_and_last_day(input("please enter month, e.g. Mar-00: "))
print("first day : ",first)
print("last day : ",last)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.