简体   繁体   中英

how to convert python time.time() to date format for sql insertion

I have the following script:

import time
start = time.time()
end = time.time()
runtime = end - start

I am trying to insert the start, end, and runtime variables into a database table. I am currently getting

cx_Oracle.DatabaseError: ORA-00932: inconsistent datatypes: expected DATE got NUMBER

this is because start and end are integers and I need them to be in a date format.

my attempt was to convert it this way:

start.strftime('%Y-%m-%d %H:%M:%S')

but this is not working. I would like to use the variables start and end and convert them to an appropriate format using the time module.

Try using datetime instead

from datetime import datetime

start = datetime.now() # Type: datetime.datetime
end = datetime.now() # Type: datetime.datetime
runtime = end - start
runtime.total_seconds() # Type: float

Edit: Using the time module:

import time
start = time.time()
end = time.time()
start_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start))
end_as_str = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(end))

In case you prefer it as a time.struct_time , then you can add

start_as_struct = time.strptime(start_as_str , '%Y-%m-%d %H:%M:%S')
end_as_struct = time.strptime(end_as_str , '%Y-%m-%d %H:%M:%S')

However, if you want it as datetime, then you will need to use the first module

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM