python 读取当前系统日期并输入文本文件

wixjitnu  于 2023-02-21  发布在  Python
关注(0)|答案(1)|浏览(133)

有人能帮我做作业吗?

import datetime

x = datetime.datetime.now()
print(x)
text = x
plik = open("data.txt", "w", encoding="utf-8")
plik.write(text)
plik.close()

怎么做呢?

plicqrtu

plicqrtu1#

您需要的内容如下:

import datetime # imports the datetime library
x = str(datetime.datetime.now()) # sets a variable x to be the current datatime, converted to string format

with open("data.txt", 'w+') as f: # creates (or opens and will overwrite if already exists) the file data.txt and changes the reference to be f
   f.write(x) # writes to data.txt the contents of the x variable

上面代码的问题在于datetime.datetime.now()没有返回str类型,而是返回datetime.datetime类型,Python不能直接编写该类型。

相关问题