Ernesto Ruiz
Ernesto Ruiz

Reputation: 820

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)

Upvotes: 0

Views: 968

Answers (4)

Adam Strauss
Adam Strauss

Reputation: 1999

It can be done by just importing/using datetime library and here you can see how.

By passing string date into method.

import datetime

def convert_string_to_datetime(self, datetime_in_string):
    datetime_in_string = str(datetime_in_string)
    datetime_format = "%Y-%m-%d %H:%M:%S"
    datetime_in_datetime_format = datetime.datetime.strptime(datetime_in_string, datetime_format)
    return datetime_in_datetime_format

new_datetime_field = convert_string_to_datetime(datetime_in_string)

By modifying with in single line

import datetime

new_datetime_field = datetime.datetime.strptime(YOUR_DATETIME_IN_STRING, "%Y-%m-%d %H:%M:%S")

After converting into datetime now comparison is possible like.

if new_datetime_field > odoo_datetime_field:
   pass

Upvotes: 0

Ajay
Ajay

Reputation: 5347

b='08/2021'
a=b.split('/')
import calendar
import datetime
z=(str(calendar.monthrange(int(a[1]),int(a[0]))[1])+'-'+b.replace('/','-'))
d=datetime.datetime.strptime(z,'%d-%m-%Y').date()

print(d)
n=datetime.date.today()
print(n)
n<d

Output:

2021-08-31
2021-01-28

True

Upvotes: 0

Kirk
Kirk

Reputation: 1845

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)

Upvotes: 3

Gab
Gab

Reputation: 3520

This examples shows you how to convert '02/2020' to a Python datetime and how to get the last day of that month. You can use it to compare the result to another datetime:

import datetime
from dateutil.relativedelta import relativedelta

date = '02/2020'
last_day = datetime.datetime.strptime(date, '%m/%Y') + relativedelta(day=31)
# last_day will be a datetime of the last day of the month which you can use to compare against another datetime

In this example, the result is datetime.datetime(2020, 2, 29, 0, 0) because 2020 was a leap year

Upvotes: 1

Related Questions