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

标签 python timestamp

我正在从 DB/2 表中提取创建时间戳并将其写入一个 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 在毫秒内写入零?

最佳答案

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

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

关于python - python中毫秒为零时如何将时间戳写入txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57603155/

相关文章:

python - 如何裁剪到 OpenCV 中最大的内部边界框?

python - Tkinter 值得学习吗?

python - 在 django 中,返回重定向没有给我所需的输出

python - Pandas 将 mysql int 转换为 float64

postgresql - 分块表以将 timestamptz 批量更新为 timestamp

r - 将时间戳(以秒为单位)转换为 R 中的日期格式

mysql - 确保 MySQL 字段时间戳不早于当前时间 1 小时

python - 没有 C 扩展的 Python 中的快速二维数组(矩阵)

r - 使用 dplyr 匹配两个数据帧中的时间戳

SQL 主键自动增量 vs 时间戳