Monday, November 18, 2024
Google search engine
HomeLanguagesHow to change datetime to string in SQLAlchemy query?

How to change datetime to string in SQLAlchemy query?

In this article, we are going to change DateTime to string in sqlalchemy query in the python programming language.

Database used:

Installation

Syntax to install sqlalchemy and pymysql:

pip install sqlalchmey pymysql

Note: pymysql is a dependency of sqlalchemy which we need to install for this post

First of all, we need to import the module and connect it to the database.

Python3




from sqlalchemy import create_engine
  
user, password, host, database = 'root', '123', 'localhost', 'neveropen'
engine = create_engine(
    url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
  
connection = engine.connect()
  
table_name = 'to_do_list'


Method 1: Using convert function of SQL

So, SQL has a convert function that can be used to change datatype of the column.

The syntax of the function is :

CONVERT(column_name , datatype)

This will convert the column to the given datatype and return the values accordingly.

The SQL query will look like :

SELECT CONVERT(column_name , CHAR) FROM table_name;

We are converting to CHAR as it is one of the data types of string in SQL.

Example:

Python3




from sqlalchemy import create_engine
  
user, password, host, database = 'root', '123', 'localhost', 'neveropen'
engine = create_engine(
    url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
  
connection = engine.connect()
  
table_name = 'to_do_list'
  
query = f'SELECT CONVERT(start_datetime,char) FROM {table_name}'
result = connection.execute(query)
  
for elem in result:
    value = elem[0]
    print(value, type(value))


Output:

Method 2: Using the str function of python :

In this method, we will write a normal “SELECT” query of SQL, execute it, fetch the result and then apply the str function to change the value.

Example:

Python3




from sqlalchemy import create_engine
  
user, password, host, database = 'root', '123', 'localhost', 'neveropen'
engine = create_engine(
    url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
  
connection = engine.connect()
  
table_name = 'to_do_list'
  
query = f'SELECT start_datetime FROM {table_name}'
result = connection.execute(query)
  
for elem in result:
    value = elem[0]
    print(value, type(value))
    converted_value = str(value)
    print(converted_value, type(converted_value))
    # just a line for much more readable output
    print("____________________________\n")


Output:

RELATED ARTICLES

Most Popular

Recent Comments