Created
December 3, 2024 22:19
-
-
Save mzhang77/d8963d79f5adfee1e195327b25bd4418 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
from datetime import datetime | |
# Get Unix epoch time (1970-01-01 00:00:00) | |
epoch_time = datetime.utcfromtimestamp(0) # Unix time 0 in UTC | |
# MySQL-compatible timestamp string | |
formatted_time = epoch_time.strftime('%Y-%m-%d %H:%M:%S') | |
# Database connection | |
conn = mysql.connector.connect( | |
host="127.0.0.1", | |
port=4000, | |
user="root", | |
password="", | |
database="test" | |
) | |
cursor = conn.cursor() | |
cursor.execute("drop table if exists unix_epoch_time_test") | |
cursor.execute("create table unix_epoch_time_test(id int primary key auto_increment, time_col timestamp(6) null default null)") | |
# Insert query | |
sql = "INSERT INTO unix_epoch_time_test (time_col) VALUES (%s)" | |
data = (formatted_time,) | |
# Execute the query | |
cursor.execute(sql, data) | |
conn.commit() | |
print(f"Inserted time: {formatted_time}") | |
sql = "SELECT id, time_col FROM unix_epoch_time_test" | |
cursor.execute(sql) | |
print("Read time from database") | |
for row in cursor.fetchall(): | |
print(f"ID: {row[0]}, time_col: {row[1]}") | |
# Close connection | |
cursor.close() | |
conn.close() | |
''' | |
Inserted time: 1970-01-01 00:00:00 | |
Read time from database | |
ID: 1, time_col: 1970-01-01 00:00:00 | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment