Home > Enterprise >  How to format python script output
How to format python script output

Time:07-30

I'm a real newbie in Python. Got together a script which reads temperature, pressure, etc. from a BMP180 sensor connected to a raspberry. Everything works fine but the output which is inserted into a table is a bit long in altitude.

I was wondering if someone could help me how do i format the altitude to have only two decimals ?

Here's what i've got:

# bmp180_logger.py
# reads the ambient temperature, pressure and altitude from the sensor module and writes it to the SQL
# database on the LAMP server

import mysql.connector
import datetime

# Import the bmp180 result 
from sensor import BMP180

# I2C bus=1, Address=0x77
bmp = BMP180(1, 0x77, 3)

# Get the temperature from the sensor module
t = bmp.temperature()

# Get the pressure from the sensor module
p = bmp.pressure()

#Get the current date & time
now = datetime.datetime.now()
date = now.strftime("%Y-%m-%d")
time = now.strftime("%H:%M:%S")

# Get the altitude from the sensor module
# Look up mean sea level pressure from local observatory.
# 1016.9 hPa is only for example.
a = p.altitude(msl=1016.9)

# print all the values
print(t.C)   # temperature in Celsius
print(p.hPa) # pressure in hPa
print(a.m)   # altitude in Metre
print (date) # current date
print (time) # current time

# The IP address of the device and its name are set as a user in the SQL database
# Connect the database object
db = mysql.connector.connect(user='bmp180', password='test', host='127.0.0.1', database='BMP180')

# Set a cursor object
cursor = db.cursor()


try:
    # Insert into the database
    cursor.execute("insert into weather_data(temperature_celsius, pressure_hPa, altitude_meters, date, time) values(%s,%s,%s,%s,%s)", (str(t.C),str(p.hPa),str(a.m),str(date),str(time)))
    # Commit the changes
    db.commit()
    cursor.close()
    db.close()
    # Unless there is a problem
except Exception as error:
    print("error: There was a problem inserting data in the database")
    print(error)
    # Rollback db transaction
    db.rollback()


    # Close the database object
    db.close()

The output is like this:

26.1
982.84
286.4581156518178 # this i would like to format to have only two decimals e.g. 286.45
2022-07-29
10:03:45

But it should be as "a.m" as that's what I'm inserting into the table.. Hope it's understandable what I'm trying to achieve.

Thanks guys, really appreciate the help in advance.

CodePudding user response:

You can format print a float value with specific number of digits after comma like this:

print("%.2f" % a.m)

CodePudding user response:

Change print(a.m) to print(f"{a.m:.2f}")

The second string is a format string, and the .2f after a.m states that the number is a float, and should only output two decimal places.

Full documentation and other syntaxes are here.

CodePudding user response:

nvm i've got it ! the insert should be formatted also like that:

cursor.execute("insert into weather_data(temperature_celsius, pressure_hPa, altitude_meters, date, time) values(%s,%s,%s,%s,%s)", (str(t.C),str(p.hPa),str(f"{a.m:.2f}"),str(date),str(time)))

Thanks guys !

  • Related