what is the proper way to convert between mysql datetime and python timestamp?

Bite Code
Published on Apr, 08 2024 1 min read 1 comments
image

according to http://dev.mysql.com/doc/refman/5.0/en/datetime.html. i got to find a way to convert the string value 'YYYY-MM-DD HH:MM:SS' to a timestamp int.

i looked up in python's doc.

i tried:

print(time.strptime('2013-01-12 15:27:43', '%Y-%m-%d %H:%M:%S'))   

python give me a result like this.

time.struct_time(tm_year=2013, tm_mon=1, tm_mday=12, tm_hour=15, tm_min=27, tm_sec=43, tm_wday=5, tm_yday=12, tm_isdst=-1)

i tried this to convert timestamp to YYYY-MM-DD HH:MM:SS format

print(time.strftime('%Y-%m-%d %H:%M:%S',time.time()))

python give me a type error.

i only use timestamp to calculate time and date, i hope there's already a way in python, simple and efficient , and don't have to create temp data.

according to the answer i write two methods. hope it would be helpful

import time

def convertTimestampToSQLDateTime(value):
    return time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(value))

def convertSQLDateTimeToTimestamp(value):
    return time.mktime(time.strptime(value, '%Y-%m-%d %H:%M:%S'))

 

1 Answers

Mahabubur Rahman Apr 08, 2024 - 05:57 PM