Software engineering and personal development

Tag: python (Page 9 of 10)

How to Quickly Find the Difference Between 2 Dates in Months in Python

laptop on brown wooden table
Photo by XPS on Unsplash

Finding the number of days is usually quite popular and well documentated. There can also be cases when we need to find a difference in terms of weeks or even months.

If you want to find the difference in months between 2 dates, then here is a quick Python script to help you do that.

For example, between October 2018 and November 2021, there isn’t just a month difference. There is also a difference in years as well.

Let us assume that we don’t have dates prepared yet, so we initialize 2 variables with 2 dates.

After that, we find the difference in terms of number of months in between.

We should keep in mind that we may have dates that are in different years, and it’s not enough to think that we can just subtract two dates.  Because of that, we need to also find the difference in years.

Here is the entire script:

You may get the impression that we may have a negative number in the end, since we are subtracting the number representing a month from another month.

To illustrate, let us assume that we have the following:

Now, since we are subtracting the number of months from the first date and 3 < 12, we will indeed get -9. However, we also have in the end a difference in years that is equal 1, since 2021 – 2020 = 1.

Hence, we will add 12 to -9, and in the end we get the result equal to 3:

That’s pretty much it.

I hope you find this useful.

How To Compare A Number With 2 Other Numbers In Python Just Like In Math

person using MacBook Pro
Photo by Glenn Carstens-Peters

Python is one of the most popular programming languages these days, as it can be used in many areas.

Part of the reason why it is so popular is the fact that it has a lot of helpful libraries that can be used.

I have been using it for quite some time now but didn’t know that you could do one type of comparison which is very intuitive and is widely used in Math.

Continue reading

A repository with the example of printing “Hello World” in a lot of programming languages

Img source: yen.io

Hello world!

One of the first things that you are instructed to do when you start to learn to programme, or when you are simply learning a new programming language, is doing something really simple. One of the first steps that you do is print a simple text. As you are reading this, you probably may know which text is the most common and the one that I am referring to. Continue reading

« Older posts Newer posts »

© 2024 Fatos Morina

Theme by Anders NorenUp ↑