Categories
Python Answers

How to create a range of dates in Python?

Sometimes, we want to create a range of dates in Python.

In this article, we’ll look at how to create a range of dates in Python.

How to create a range of dates in Python?

To create a range of dates in Python, we can use the datetime module with list comprehension.

For instance, we write:

import datetime

base = datetime.datetime.today()
date_list = [base - datetime.timedelta(days=x) for x in range(10)]
print(date_list)

We call datetime.datetime.today to get today’s `date and time.

Then we compute the date from 9 days before today to today by using base - datetime.timedelta(days=x) for x in range(10).

And then we put the values into a list.

Therefore, date_list is:

[datetime.datetime(2021, 10, 24, 19, 15, 0, 832006), datetime.datetime(2021, 10, 23, 19, 15, 0, 832006), datetime.datetime(2021, 10, 22, 19, 15, 0, 832006), datetime.datetime(2021, 10, 21, 19, 15, 0, 832006), datetime.datetime(2021, 10, 20, 19, 15, 0, 832006), datetime.datetime(2021, 10, 19, 19, 15, 0, 832006), datetime.datetime(2021, 10, 18, 19, 15, 0, 832006), datetime.datetime(2021, 10, 17, 19, 15, 0, 832006), datetime.datetime(2021, 10, 16, 19, 15, 0, 832006), datetime.datetime(2021, 10, 15, 19, 15, 0, 832006)]

Conclusion

To create a range of dates in Python, we can use the datetime module with list comprehension.

Categories
Python Answers

How to calculate the date six months from the current date using the datetime Python module?

Sometimes, we want to calculate the date six months from the current date using the datetime Python module.

In this article, we’ll look at how to calculate the date six months from the current date using the datetime Python module.

How to calculate the date six months from the current date using the datetime Python module?

To calculate the date six months from the current date using the datetime Python module, we can use the relativetimedelta function.

For instance, we write:

from datetime import date
from dateutil.relativedelta import relativedelta

six_months = date(2020, 1, 1) + relativedelta(months=+6)
print(six_months)

We call date to create a date object.

Then we add 6 months to the date and return the new date with + relativedelta(months=+6).

And then we assign the sum to six_months.

Therefore, six_months is 2020-07-01.

Conclusion

To calculate the date six months from the current date using the datetime Python module, we can use the relativetimedelta function.

Categories
Python Answers

How to compare version numbers in Python?

Sometimes, we want to compare version numbers in Python.

In this article, we’ll look at how to compare version numbers in Python.

How to compare version numbers in Python?

To compare version numbers in Python, we can use the packaging module.

We can install it with:

pip install packaging

For instance, we write:

from packaging import version

is_less = version.parse("2.3.1") < version.parse("10.1.2")
print(is_less)

We call version.parse with the version strings.

And then we can compare the parsed version objects with the usual comparison operators.

Therefore, is_less is True.

Conclusion

To compare version numbers in Python, we can use the packaging module.

Categories
Python Answers

How to use async and await with Python?

Sometimes, we want to use async and await with Python to run async tasks.

In this article, we’ll look at how to use async and await with Python.

How to use async and await with Python?

To use async and await with Python, we can use the asyncio module and the async and await keywords.

For instance, we write:

import asyncio


async def async_foo():
    print("async_foo started")
    await asyncio.sleep(1)
    print("async_foo done")


async def main():
    asyncio.ensure_future(async_foo())
    print('Do some actions 1')
    await asyncio.sleep(1)
    print('Do some actions 2')
    await asyncio.sleep(1)
    print('Do some actions 3')


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

We define the async async_foo function which prints some text and calls asyncio.sleep to pause the function for 1 second.

Then we have the async main function that asyncio.ensure_future method to create a task from the async_foo function and run it.

And then we call asyncio.sleep again with await to pause the function.

Next, we call asyncio.get_event_loop to return the event loop object.

And then we call loop.run_until_complete with main() to run main.

Therefore, we see:

Do some actions 1
async_foo started
Do some actions 2
async_foo done
Do some actions 3

printed with some pauses in between printing each line.

Conclusion

To use async and await with Python, we can use the asyncio module and the async and await keywords.

Categories
Python Answers

How to save a Numpy array as an image with Python?

Sometimes, we want to save a Numpy array as an image with Python.

In this article, we’ll look at how to save a Numpy array as an image with Python.

How to save a Numpy array as an image with Python?

To save a Numpy array as an image with Python, we can use the Image.fromarray method.

For instance, we write:

from PIL import Image
import numpy

w, h = 200, 100
img = numpy.zeros((h, w, 3), dtype=numpy.uint8)

img[:] = (0, 0, 255)

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Image.fromarray(img).convert("RGB").save("art.png")

We call numpy.zeroes to generate an array and assign that to img.

Then we set the entries in img to the (0, 0, 255) tuple.

We then change the colors of some of the entries in the img to (255, 0, 0) with:

x, y = 40, 20
img[y:y + 30, x:x + 50] = (255, 0, 0)

Finally, we call Image.fromarray with the img array to create an image from img.

Then we call convert with 'RGB' and save to convert the image to RGB color and save it to the given path.

Now we should see an art.png image file with a blue background and a red rectangle inside.

Conclusion

To save a Numpy array as an image with Python, we can use the Image.fromarray method.