Categories
Python Answers

How to add days to a date in Python?

Sometimes, we want to add days to a date in Python.

In this article, we’ll look at how to add days to a date in Python.

How to add days to a date in Python?

To add days to a date in Python, we can use the datetime.timedelta method and the + operator.

For instance, we write:

import datetime

start_date = '10/01/2021'
date_1 = datetime.datetime.strptime(start_date, "%m/%d/%Y")

end_date = date_1 + datetime.timedelta(days=10)
print(end_date)

We call datetime.datetime.strptime with start_date and the format string to convert the date string to a date object.

%m is the 2 digit month’s format code.

%d is the 2 digit day’s format code.

%Y is the 4 digit year’s format code.

Then we add 10 days to date_1 by using datetime.timedelta(days=10) to create the 10 days time delta object.

And then we use the + operator to add 10 days to date_1.

So end_date is 2021-10-11 00:00:00.

Conclusion

To add days to a date in Python, we can use the datetime.timedelta method and the + operator.

Categories
Python Answers

How to make a comma-separated string from a list of strings in Python?

Sometimes, we want to make a comma-separated string from a list of strings in Python.

In this article, we’ll look at how to make a comma-separated string from a list of strings in Python.

How to make a comma-separated string from a list of strings in Python?

To make a comma-separated string from a list of strings in Python, we can use the string’s join method.

For instance, we write:

my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
print(my_string)

We call ''.join with my_list to join each entry in my_list with commas.

Therefore, my_string is 'a,b,c,d'.

Conclusion

To make a comma-separated string from a list of strings in Python, we can use the string’s join method.

Categories
Python Answers

How to support equivalence (“equality”) check in Python classes?

Sometimes, we want to support equivalence ("equality") check in Python classes.

In this article, we’ll look at how to support equivalence ("equality") check in Python classes.

How to support equivalence ("equality") check in Python classes?

To support equivalence ("equality") check in Python classes, we can override the __eq__ method in the Python class.

For instance, we write:

class Number:
    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        if isinstance(other, Number):
            return self.number == other.number
        return False

n1 = Number(1)
n2 = Number(1)
print(n1 == n2)

to add the __eq__ method which checks for the value of self.number to determine equality of a Number instances instead of using the default way, which is to compare object ID for equality.

We only do the check if other is a Number instance. Otherwise, we return False directly.

Next, we create 2 Number instances with the same value for self.number.

Therefore, n1 and n2 should be equal according to our check, and so True is printed.

Conclusion

To support equivalence ("equality") check in Python classes, we can override the __eq__ method in the Python class.

Categories
Python Answers

How to write a Python list of lists to a CSV file?

Sometimes, we want to write a Python list of lists to a CSV file.

In this article, we’ll look at how to write a Python list of lists to a CSV file.

How to write a Python list of lists to a CSV file?

To write a Python list of lists to a CSV file, we can use the csv module.

For instance, we write:

import csv

a = [[1.2, 'abc', 3], [1.2, 'werew', 4], [1.4, 'qew', 2]]

with open("out.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(a)

to pass the nested list a as the argument of writer.writerows to write the file to the out.csv file.

We open the out.csv file with 'w' permission to let us write to the file.

And we set the new line character to an empty string as specified with newline="".

Then we call csv.writer with f to create the writer object and call writerows to write to the file.

Therefore, out.csv has:

1.2,abc,3
1.2,werew,4
1.4,qew,2

Conclusion

To write a Python list of lists to a CSV file, we can use the csv module.

Categories
Python Answers

How to write Unicode text to a text file with Python?

Sometimes, we want to write Unicode text to a text file with Python.

In this article, we’ll look at how to write Unicode text to a text file with Python.

How to write Unicode text to a text file with Python?

To write Unicode text to a text file with Python, we can call the file handle’s write method with a Unicode encoded string.

For instance, we write:

foo = u'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'
f = open('test', 'w')
f.write(foo)
f.close()

f = open('test', 'r')
print(f.read())

We define the string foo with a Unicode string.

Then we open the test file with open with write permission.

Next, we call f.write with foo and then close the file with close.

Then to read the file, we call open again with the file path and 'r' to get read permission.

And then we call f.read.

Therefore print should print 'Δ, Й, ק, ‎ م, ๗, あ, 叶, 葉, and 말.'.

Conclusion

To write Unicode text to a text file with Python, we can call the file handle’s write method with a Unicode encoded string.