Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

How to convert a 'day/month' string to date in python and compare it with an Odoo date field?

I have a day/month string, I want to convert that string to date object and compare the last day of that month to another date

Example:
For 08/2021 (august, 2021) I want to compare the last day of that month (31-08-2021) to another date (date field),

For 02/2020 I what to compare 29-02-2020 < another_date (date field)

For 02/2021 I what to compare 28-02-2020 < another_date (date field)

question from:https://stackoverflow.com/questions/65930316/how-to-convert-a-day-month-string-to-date-in-python-and-compare-it-with-an-odo

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use calendar.monthrange to find the last day in the month if you don't want to add dateutil.

import calendar
from datetime import datetime

def get_last_day_date(year_month_str):
     date = datetime.strptime(year_month_str, "%m/%Y")
     last_day = calendar.monthrange(date.year, date.month)[1]
     return datetime(date.year, date.month, last_day)

get_last_day_date("08/2020")
# datetime.datetime(2020, 8, 31, 0, 0)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...