使用 .write() 追加文件,但想使用变量
Using .write() to append a file, but want to use a variable
在我的代码中,我打开了一个文件,我想将当前日期和时间附加到该文件。我正在使用 datetime 获取日期
currenttime = datetime.datetime.now()
并将当前 date/time 分配给名为 "currenttime"
的变量
print(currenttime)
with open("log.txt", "a") as f:
log.write(currenttime)
当我尝试这样做时,出现错误:
TypeError: write() argument must be str, not datetime.datetime
这是因为您正在尝试将日期时间对象写入文本文件。您可以通过几种不同的方式转换日期时间对象以使其可写,例如:
str(currenttime)
或
currenttime.isoformat()
即:
with open("log.txt", "a") as f:
f.write(str(currenttime))
如果您想使用特殊格式的时间戳,您可以使用 strftime
,例如:
In [1]: datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Out[1]: '2016-03-01 23:52:36'
您可以在此处阅读有关格式化日期时间的更多信息:https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
根据您的文件名和您要添加时间戳的事实,如果您需要日志记录,那么查看 python 中的日志记录模块可能是个好主意。它非常适合该目的,而不是手动写入文件:https://docs.python.org/2/library/logging.html
将 currenttime
转换为字符串 str()
:
with open("log.txt", "a") as f:
f.write(str(currenttime))
请注意,您应该使用 f.write()
写入您的文件,而不是 log.write()
。
类型转换 datetime
对象到 str
log.write(str(currenttime))
在我的代码中,我打开了一个文件,我想将当前日期和时间附加到该文件。我正在使用 datetime 获取日期
currenttime = datetime.datetime.now()
并将当前 date/time 分配给名为 "currenttime"
的变量print(currenttime)
with open("log.txt", "a") as f:
log.write(currenttime)
当我尝试这样做时,出现错误:
TypeError: write() argument must be str, not datetime.datetime
这是因为您正在尝试将日期时间对象写入文本文件。您可以通过几种不同的方式转换日期时间对象以使其可写,例如:
str(currenttime)
或
currenttime.isoformat()
即:
with open("log.txt", "a") as f:
f.write(str(currenttime))
如果您想使用特殊格式的时间戳,您可以使用 strftime
,例如:
In [1]: datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Out[1]: '2016-03-01 23:52:36'
您可以在此处阅读有关格式化日期时间的更多信息:https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
根据您的文件名和您要添加时间戳的事实,如果您需要日志记录,那么查看 python 中的日志记录模块可能是个好主意。它非常适合该目的,而不是手动写入文件:https://docs.python.org/2/library/logging.html
将 currenttime
转换为字符串 str()
:
with open("log.txt", "a") as f:
f.write(str(currenttime))
请注意,您应该使用 f.write()
写入您的文件,而不是 log.write()
。
类型转换 datetime
对象到 str
log.write(str(currenttime))