在python中,当毫秒为零时,如何将时间戳写入txt文件

在python中,当毫秒为零时,如何将时间戳写入txt文件,python,timestamp,Python,Timestamp,我正在从DB/2表中提取create timestamp,并将其写入一个txt文件,以便在以后的处理中使用。Python正确写入时间戳,除非毫秒为零。当毫秒为零时,它不会写入毫秒。如何让它写入零毫秒 import ibm_db import datetime sql = ("SELECT CRT_TS FROM TABLE_TIMEST WHERE DATE(CRT_TS) > '2018-01-01' WITH UR;") stmt = ibm_db_exec_immediate(co

我正在从DB/2表中提取create timestamp,并将其写入一个txt文件,以便在以后的处理中使用。Python正确写入时间戳,除非毫秒为零。当毫秒为零时,它不会写入毫秒。如何让它写入零毫秒

import ibm_db
import datetime

sql = ("SELECT CRT_TS FROM TABLE_TIMEST WHERE DATE(CRT_TS) > '2018-01-01' WITH UR;")
stmt = ibm_db_exec_immediate(conn,sql)
fle = open("c:\Test\tstamps.txt","w+")
dictionary = ibm_db.fetch_both(stmt)
while dictionary != False

    fle.write(str(dictionary["CRT_TS"]))
    dictionary = ibm_db.fetch_both(stmt)

fle.close()
表上的时间戳为:

2018-06-12 18:50:55.125489
2018-06-12 18:57:52.000000
2018-06-12 18:58:42.152469
我希望在我的输出文件中得到相同的结果,而不是得到:

2018-06-12 18:50:55.125489
2018-06-12 18:57:52
2018-06-12 18:58:42.152469

如何让python以毫秒为单位写入零?

您可以首先在dataframe中获取数据,然后执行以下操作:

import ibm_db
import datetime

sql = ("SELECT CRT_TS FROM TABLE_TIMEST WHERE DATE(CRT_TS) > '2018-01-01' WITH UR;")
stmt = ibm_db_exec_immediate(conn,sql)
fle = open("c:\Test\tstamps.txt","w+")
dictionary = ibm_db.fetch_both(stmt)
while dictionary != False

    fle.write(str(dictionary["CRT_TS"]))
    dictionary = ibm_db.fetch_both(stmt)

fle.close()
d1 = '2018-06-12 18:57:52.000000'
d1 = pd.Timestamp(d1)
print(d1.strftime('%Y-%m-%d %H:%M:%S.%f'))

这将转换datetime对象中的时间字符串,并将其转换回具有浮动秒数的字符串

from datetime import datetime 

fle.write(datetime.strptime(str(dictionary["CRT_TS"]), '%Y-%m-%d %H:%M:%S.%f').strftime('%Y-%m-%d %H:%M:%S.%f'))

您的时间戳似乎已经是datetime对象,因此您只需使用它们自己的strftime方法:

fle.write(字典[“CRT”].strftime(“%Y-%m-%d%H:%m:%S.%f”)