Categories
Python Answers

How to parse a date string and change its format with Python?

Sometimes, we want to parse a date string and change its format with Python.

In this article, we’ll look at how to parse a date string and change its format with Python.

How to parse a date string and change its format with Python?

To parse a date string and change its format with Python, we can use the datetime.datetime.striptime method to parse a date string into a date object.

And then we call strftime to convert the date object back to a string.

For instance, we write:

import datetime

d = datetime.datetime.strptime('Mon Feb 15 2020',
                               '%a %b %d %Y').strftime('%d/%m/%Y')
print(d)

We call datetime.datetime.strptime with the date string and the format string of the date respectively.

%a is the abbreviation of the day of the week.

%b is the abbreviation of the month.

%d is the day of the month.

And %Y is the year.

We then call strftime to return a date string with the format we want.

%m is the 2 digit month.

Therefore, d is '15/02/2020'.

Conclusion

To parse a date string and change its format with Python, we can use the datetime.datetime.striptime method to parse a date string into a date object.

And then we call strftime to convert the date object back to a string.

Categories
Python Answers

How to read JSON from a file with Python?

Sometimes, we want to read JSON from a file with Python.

In this article, we’ll look at how to read JSON from a file with Python.

How to read JSON from a file with Python?

To read JSON from a file with Python, we can use the json.loads method.

For instance, we write:

strings.json

{
  "strings": [
    {
      "name": "city",
      "text": "City"
    },
    {
      "name": "phone",
      "text": "Phone"
    },
    {
      "name": "address",
      "text": "Address"
    }
  ]
}

main.py

import json

with open('strings.json') as f:
    d = json.load(f)
    print(d)

We call open with the file path to the JSON file.

Then we call json.load with the opened file.

And then we print d which has the JSON string read from the file.

Therefore, d is:

{'strings': [{'name': 'city', 'text': 'City'}, {'name': 'phone', 'text': 'Phone'}, {'name': 'address', 'text': 'Address'}]}

Since we used the with statement, the file will automatically close once we’re done using it.

Conclusion

To read JSON from a file with Python, we can use the json.loads method.

Categories
Python Answers

How to combine two dicts and add values for keys that appear in both with Python?

Sometimes, we want to combine two dicts and add values for keys that appear in both with Python.

In this article, we’ll look at how to combine two dicts and add values for keys that appear in both with Python.

How to combine two dicts and add values for keys that appear in both with Python?

To combine two dicts and add values for keys that appear in both with Python, we can use the Counter class from the collections module.

For instance, we write:

from collections import Counter
A = Counter({'a':1, 'b':2, 'c':3})
B = Counter({'b':3, 'c':4, 'd':5})
C =  A + B
print(C)

We create Counter instances from 2 dicts and assign them to A and B respectively.

Then we add the values of each dict entry together by using the + operator and assign the result to C.

Therefore, we see that C is Counter({'c': 7, 'b': 5, 'd': 5, 'a': 1}) from what we printed.

Conclusion

To combine two dicts and add values for keys that appear in both with Python, we can use the Counter class from the collections module.

Categories
Python Answers

How to use global variables between files in Python?

Sometimes, we want to use global variables between files in Python.

In this article, we’ll look at how to use global variables between files in Python.

How to use global variables between files in Python?

To use global variables between files in Python, we can use the global keyword to define a global variable in a module file.

Then we can import the module in another module and reference the global variable directly.

For instance, we write:

settings.py

def init():
    global myList
    myList = []

subfile.py

import settings


def stuff():
    settings.myList.append('hi')

main.py

import settings
import subfile

settings.init()
subfile.stuff()
print(settings.myList[0])

We import the settings and subfile modules in main.py.

Then we call settings.init to create the myList global variable and assign it to an empty array.

Then we call subfile.stuff to call settings.myList.append to add an entry to the settings.myList global variable.

Then we print the value of settings.myList[0], which is 'hi'.

Conclusion

To use global variables between files in Python, we can use the global keyword to define a global variable in a module file.

Then we can import the module in another module and reference the global variable directly.

Categories
Python Answers

How to generate the Fibonacci Sequence with Python?

Sometimes, we want to generate the Fibonacci Sequence with Python.

In this article, we’ll look at how to generate the Fibonacci Sequence with Python.

How to generate the Fibonacci Sequence with Python?

To generate the Fibonacci Sequence with Python, we can create a generator function that yields the value the sequence.

For instance, we write:

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b


for index, fibonacci_number in zip(range(10), fib()):
    print(index, fibonacci_number)

We create the fib function that uses yield to return the Fibonacci sequence by assigning b to a and b to a + b.

Then we use a for loop that zips range(10) and the iterator returned by the fib function together to generate the first 10 Fibonacci sequence values.

In the loop body, we print the index and fibonacci_number values.

Therefore, we see:

0 0
1 1
2 1
3 2
4 3
5 5
6 8
7 13
8 21
9 34

logged.

Conclusion

To generate the Fibonacci Sequence with Python, we can create a generator function that yields the value the sequence.