Ensuring timestamp storage in UTC with SQLAlchemy
Last Updated :
16 Oct, 2023
In modern web applications, handling timestamps is a common requirement. Storing timestamps in a standardized format, such as UTC (Coordinated Universal Time), ensures consistency and simplifies data manipulation across different time zones. This article explores best practices and provides a step-by-step implementation guide for storing timestamps in UTC using SQLAlchemy.
Ensuring Timestamp Storage in UTC with SQLAlchemy
SQLAlchemy, a powerful Python library for working with databases, offers various techniques to ensure proper storage and retrieval of timestamps in UTC. When working with timestamps in a database using SQLAlchemy in Python, it is crucial to ensure consistent time representation across different time zones. Storing timestamps in UTC (Coordinated Universal Time) format helps prevent issues related to time zone conversions and daylight saving time changes.
Steps to Ensure Timestamp Storage in UTC with SQLAlchemy
Let us see a step-by-step process of storing timestamp in UTC using SQLAlchemy in Python.
Step 1: Create a schema in the MySQL Server
The first step would be to create a schema in MySQL Workbench if it does not exist already.
Creating a Schema in MySQL ServerStep 2: Import necessary modules
Then, import the sqlalchemy modules that are required to perform basic functionalities of SQLAlchemy such as creating a connection, defining columns, etc. The declarative_base module provides a base class for declarative class definitions. It is used to create a base class from which all mapped classes will inherit. The sessionmaker provides a way to interact with the database.
from sqlalchemy import create_engine, Column, Integer, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Step 3: Create a Database Connection
To begin, establish a connection to your MySQL database using SQLAlchemy. Replace the username, password, host and database name with the actual credentials that you have given to your database. If your password contains the @
symbol, it can interfere with the connection URL's syntax, as the '@'
symbol is used to separate the username and password in the URL. To include a special character like '@'
in your password, you need to URL-encode it. The quote_plus of urllib.parse module is used to URL-encode special characters in the database password. It takes a string as input and returns the encoded version.
from urllib.parse import quote_plus
password = 'password'
encoded_password = quote_plus(password)
db_url = f'mysql+mysqlconnector://username:{encoded_password}@localhost/database_name'
Step 4: Defining the Table Structure
Next, you can define your table structure using Python classes. Define your table class with the desired table name and columns. The 'created_at' column is defined as a DateTime type with the 'timezone=True' argument, ensuring it stores time zone-aware timestamps. The 'server_default=func.now()' sets the default value for this column to the current timestamp.
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'table_name'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
Step 5: Creating the Table
With the table structure defined, create the table in your MySQL database using the following code. This line of code will generate the table based on the structure defined in MyTable
.
Base.metadata.create_all(engine)
Step 6: Store timestamps in UTC
Create a new instance of MyTable
, and by adding it to the session and committing the changes, a new record with the current UTC timestamp is inserted into the table.
Session = sessionmaker(bind=engine)
session = Session()record = MyTable()
session.add(record)
session.commit()
Step 7: Retrieving and Displaying Timestamps
To retrieve and display the stored UTC timestamps, query the table and access the 'created_at' column. The 'result' represents the retrieved record.
result = session.query(MyTable).first()
print("ID:", result.id)
print("Created At (UTC):", result.created_at)
Example:
Python
from sqlalchemy import create_engine, Column, Integer, DateTime, func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
from urllib.parse import quote_plus
# Encode the password with the @ symbol
password = 'your password'
encoded_password = quote_plus(password)
# Connect to the database
engine = create_engine(
'mysql+mysqlconnector://root:'+encoded_password+'@localhost:3306/gfg')
# Create the table
Base.metadata.create_all(engine)
# Create a session
Session = sessionmaker(bind=engine)
session = Session()
# Insert a record with the current timestamp
record = MyTable()
session.add(record)
session.commit()
# Retrieve and print the record
result = session.query(MyTable).first()
print("ID:", result.id)
print("Created At (UTC):", result.created_at)
Output:
UTC timestamp in SQLAlchemyThe output displays the ID and the UTC timestamp for the retrieved record.
UTC timestamp storage in SQLAlchemy
Similar Reads
Convert datetime to unix timestamp in SQLAlchemy model
When dealing with databases date and time are considered to be one of the most important attributes for any entity. With such data, we often encounter some common task of converting DateTime to a Unix timestamp. In this article, we will learn how we can convert datetime to Unix timestamp in SQLAlche
5 min read
Get UTC timestamp in Python
UTC timestamp represents a specific point in time as measured from the "Unix epoch" â January 1, 1970, 00:00:00 UTC. This timestamp is often used in computing because it is not affected by time zones or daylight saving time, providing a consistent reference time across the globe. When working with t
3 min read
PostgreSQL Query To View with SQLAlchemy
As a software developer, it is a common task to query a PostgreSQL view. Using views which is a virtual table representing the output of a SQL query, is considered to be an efficient way when dealing with a relational database. This article covers how to query a PostgreSQL view using SQLAlchemy in P
9 min read
Pandas - Generating ranges of timestamps using Python
A timestamp is a string of characters or encrypted or encoded data that identifies the time and date of an event, usually indicating the time and date of day, and is often accurate to a fraction of a second. timestamps are used to maintain track of information. When information was created, transmit
3 min read
Using Sqlalchemy to insert MySQL Timestamp Column Values
This article is about how we can add a timestamp column with values in MYSQL along with other data in an SQL database. Timestamp is quite useful as it provides the time when that particular entity was created in the database. Here we will use SQLAlchemy as it is a popular Python programming SQL tool
3 min read
SQLAlchemy core - Update statement
In this article, we are going to see how to use the UPDATE statement in SQLAlchemy against a PostgreSQL database in Python. Creating table for demonstration Import necessary functions from the SQLAlchemy package. Establish connection with the PostgreSQL database using create_engine() function as sho
3 min read
Comparing Timestamp Dates With Date-Only Parameter in SQL
Working with date and time in databases is a common task, especially when dealing with timestamps. Comparing timestamp values with date-only parameters in SQL is important for filtering data, performing calculations, and ensuring data accuracy.In this article, we will explain the process of comparin
4 min read
How to Update Current Timestamp in MySQL?
MySQL is an easy-to-use RDBMS. Many organizations prefer to use it because of its easy maintainability, easier to prepare schemas, stored procedures, triggers, and database maintenance. In this article, let us see how to update to Current Timestamp in MySQL. Step 1: Database creation Firstly we crea
3 min read
Sqlalchemy Core With Text SQL For Date Range
SQLAlchemy Core is a low-level SQL abstraction layer of SQLAlchemy, a popular Python Object Oriented Mapping(ORM) library. It provides a way to interact with relational databases wing python code, allowing developers to write SQL Queries in a more object-oriented manner. SQLAlchemy is a python libra
2 min read
SQLalchemy Bulk insert with one to one relation
When working with databases in Python, SQLAlchemy is a popular and powerful library that provides a high-level interface for interacting with relational databases. It offers an Object-Relational Mapping (ORM) layer that allows developers to work with database tables as Python objects. In this articl
5 min read