Categories
Python Answers

How to iterate through a range of dates in Python?

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

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

How to iterate through a range of dates in Python?

To iterate through a range of dates in Python, we can use the datetime module and a while loop.

For instance, we write:

from datetime import date, timedelta

start_date = date(2021, 1, 1)
end_date = date(2021, 2, 1)
delta = timedelta(days=1)
while start_date <= end_date:
    print(start_date.strftime("%Y-%m-%d"))
    start_date += delta

We create the start_date and end_date objects with the date function.

Then we call timedelta with the magnitude of the time difference we want to increment by.

Next, we use a while loop to loop through the dates and print the dates as strings with striftime.

And then we update start_date by adding timedelta to it.

Therefore, we get:

2021-01-01
2021-01-02
2021-01-03
2021-01-04
2021-01-05
2021-01-06
2021-01-07
2021-01-08
2021-01-09
2021-01-10
2021-01-11
2021-01-12
2021-01-13
2021-01-14
2021-01-15
2021-01-16
2021-01-17
2021-01-18
2021-01-19
2021-01-20
2021-01-21
2021-01-22
2021-01-23
2021-01-24
2021-01-25
2021-01-26
2021-01-27
2021-01-28
2021-01-29
2021-01-30
2021-01-31
2021-02-01

printed.

Conclusion

To iterate through a range of dates in Python, we can use the datetime module and a while loop.

Categories
Python Answers

How to read a file in reverse order with Python?

Sometimes, we want to read a file in reverse order with Python.

In this article, we’ll look at how to read a file in reverse order with Python.

How to read a file in reverse order with Python?

To read a file in reverse order with Python, we can use the file_read_backwards module.

To install it, we run:

pip install file_read_backwards

Then we write:

from file_read_backwards import FileReadBackwards

with FileReadBackwards("file.txt", encoding="utf-8") as frb:
    for l in frb:
        print(l)

to read the file.txt file backwards.

We pass in the file path and the encoding as arguments for the FileReadBackwards constructor.

Then we loop through the iterator with the lines returned.

Therefore, is file.txt has

foo
bar
baz

Then we get:

baz
bar
foo

Conclusion

To read a file in reverse order with Python, we can use the file_read_backwards module.

Categories
Python Answers

How to get current CPU and RAM usage in Python?

Sometimes, we want to get current CPU and RAM usage in Python.

In this article, we’ll look at how to get current CPU and RAM usage in Python.

How to get current CPU and RAM usage in Python?

To get current CPU and RAM usage in Python, we can use the psutil module.

To install it, we run:

pip install psutil

Then we write:

import psutil

print(psutil.cpu_percent())
print(psutil.virtual_memory())
print(dict(psutil.virtual_memory()._asdict()))
print(psutil.virtual_memory().percent)
print(psutil.virtual_memory().available * 100 / psutil.virtual_memory().total)

to get the percentage of CPU used with cpu_percent.

virtual_memory gets the amount of available virtual memory and how much of it is used.

We can call _asdict on the object returned by virtual_memory to convert it to a dictionary.

percent, available, and total returns the percent of virtual memory used, amount of virtual memory available in bytes, and total virtual memory available in bytes respectively.

Therefore, we get something like:

0.0
svmem(total=27328045056, available=21079855104, percent=22.9, used=6097809408, free=9938751488, active=4543451136, inactive=8950083584, buffers=1948196864, cached=9343287296, shared=12705792, slab=3136671744)
{'total': 27328045056, 'available': 21079855104, 'percent': 22.9, 'used': 6097809408, 'free': 9938751488, 'active': 4543451136, 'inactive': 8950083584, 'buffers': 1948196864, 'cached': 9343287296, 'shared': 12705792, 'slab': 3136671744}
22.9
77.13634495553431

Conclusion

To get current CPU and RAM usage in Python, we can use the psutil module.

Categories
Python Answers

How to extract text from HTML file using Python?

Sometimes, we want to extract text from HTML file using Python.

In this article, we’ll look at how to extract text from HTML file using Python.

How to extract text from HTML file using Python?

To extract text from HTML file using Python, we can use BeautifulSoup.

To install it, we run:

pip install bs4

Then we write:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
html = urlopen(url).read()
soup = BeautifulSoup(html, features="html.parser")

for script in soup(["script", "style"]):
    script.extract()  
text = soup.get_text()

lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
text = '\n'.join(chunk for chunk in chunks if chunk)

print(text)

We call urllib.request.urlopen with the url we want to get the HTML text from.

Then we call read to read the response into a string.

Next, we use the BeautifulSoup constructor with html.

Then we loop through the script and style tags in the HTML string and remove them with:

for script in soup(["script", "style"]):
    script.extract()  

Then we get the text chunks and join them together with:

text = soup.get_text()

lines = (line.strip() for line in text.splitlines())
chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
text = '\n'.join(chunk for chunk in chunks if chunk)

We call splitlines to split the text into lines.

And we call strip on each line and phrase to remove any leading and trailing whitespaces.

Finally, we call join to join the substrings together into one string with newlines in between them.

Conclusion

To extract text from HTML file using Python, we can use BeautifulSoup.

Categories
Python Answers

How to convert local time string to UTC with Python?

Sometimes, we want to convert local time string to UTC with Python.

In this article, we’ll look at how to convert local time string to UTC with Python.

How to convert local time string to UTC with Python?

To convert local time string to UTC with Python, we can use the datetime and pytz modules.

For instance, we write:

from datetime import datetime
import pytz

local = pytz.timezone("America/Los_Angeles")
naive = datetime.strptime("2021-2-3 10:11:12", "%Y-%m-%d %H:%M:%S")
local_dt = local.localize(naive, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print(utc_dt)

We call pytz.timezone with the time zone string to create the local time zone object.

Then we convert a date and time string to a datetime object with datetime.strptime`.

Next, we call local.localize with the naive dattime to convert it to a local date time.

We set is_dst to None to make sure the time isn’t set to daylight saving time.

Then we call local_dt.astimezone with pytz.utc to get the UTC date time and assign it to utc_dt.

Therefore utc_dt is 2021-02-03 18:11:12+00:00.

Conclusion

To convert local time string to UTC with Python, we can use the datetime and pytz modules.