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

2024-05-10 01:21:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从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以毫秒为单位编写零?你知道吗


Tags: 文件importtxtdbsqldictionary时间fetch
3条回答

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

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

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

fle.write(dictionary["CRT_TS"].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'))

相关问题 更多 >