gpt4 book ai didi

python - 如何使用 Python 脚本在文本文件或日志文件中写入时间(本地系统时间)?

转载 作者:行者123 更新时间:2023-11-28 22:00:36 25 4
gpt4 key购买 nike

我必须编写一个测试用例,因为我正在使用在 Python 脚本上运行的 sikuli,在这里我无法在文本文件中写入本地系统时间。

import time;

localtime = time.localtime(time.time())
inp=file("C:\\Users\\%path%\\Log.txt", 'w')
inp.write('************** Full Process ****************\n')
inp.write('Local current time :', localtime) incorrect

这里我正在创建一个 .txt 文件,我还必须写时间而且我不知道如何编写代码。

最佳答案

这几乎是正确的,但是你写的时间有误:

inp.write('Local current time :', localtime)

如果你想像那样格式化一个字符串,你需要使用%操作符:

inp.write('Local current time : %s' % localtime)

此外,仅仅打印Time对象会打印出一个非常奇怪的字符串。您希望以更方便的方式书写日期,例如 YYYY/MM/DD - HH:MM:SS。你这样做:

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

所以你的代码片段将是:

import time

localtime = time.localtime(time.time())
timestring = time.strftime ('%Y/%m/%d - %H:%M:%S')
inp=file("Log.txt", 'w')
inp.write('************** Full Process ****************\n')
inp.write('Local current time : %s' % timestring)

关于python - 如何使用 Python 脚本在文本文件或日志文件中写入时间(本地系统时间)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14518740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com