Skip to content

Instantly share code, notes, and snippets.

@thegeorgenikhil
Last active January 2, 2025 09:06
Show Gist options
  • Save thegeorgenikhil/b59bf08dc7aa5fd9a09569be4d61b587 to your computer and use it in GitHub Desktop.
Save thegeorgenikhil/b59bf08dc7aa5fd9a09569be4d61b587 to your computer and use it in GitHub Desktop.
Setting UTC time in MySQL + SQLModel Base Model

Base class for SQLModel Migrations

from datetime import datetime
from sqlmodel import Field, SQLModel
from sqlalchemy import Column, text, DateTime


class BaseModel(SQLModel):
    id: int = Field(default=None, primary_key=True)

    created_at: datetime = Field(
        default=None,
        sa_column=Column(
            DateTime(timezone=True),
            server_default=text('CURRENT_TIMESTAMP'),
            nullable=False
        )
    )
    updated_at: datetime = Field(
        default=None,
        sa_column=Column(
            DateTime(timezone=True),
            server_default=text("CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"),
        )
    )    

Setting the server time to UTC

mysql --help | grep "Default options" -A 1

# Default options are read from the following files in the given order:
# /etc/my.cnf /etc/mysql/my.cnf /usr/local/mysql/etc/my.cnf ~/.my.cnf 

Add the following to one of the .cnf files

[mysqld]
default-time-zone='+00:00'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment