我正在尝试创建一个简单的输出文件,其中包含时间戳(刺激出现的时间(和刺激的颜色。
我可以只写颜色的文件,但每当我试图创建一个同时包含时间戳和颜色的文件时,我都会出错。"TypeError:无法连接'str'和'datetime.datetime'对象">
以下代码:
from psychopy import visual, core
import random
import time
import datetime
import time
from time import strftime
f = open('2015-07-15-Random-Output.txt', 'w')
print f
file = open ('2015-07-15-Random-Output.txt', 'w')
win = visual.Window([800,800],monitor="testmonitor", units="deg")
HolaMundo = "Hola Mundo"
for frameN in range(10):
MyColor = random.choice(['red','blue','green','pink','purple','orange','yellow','black','white'])
time = datetime.datetime.now()
print time
data = MyColor + str(time)
msg = visual.TextStim(win, text=HolaMundo,pos=[-4,0],color=MyColor)
msg.draw()
win.flip()
core.wait(.1)
datetime.datetime.now
file.write(time + 'n')
file.close()
datetime.datetime.now
只引用方法,不调用它。它应该是str(datetime.datetime.now())
或:
time = datetime.datetime.now()
time.strftime('%m/%d/%Y') #formats the date as a string
有关格式化的更多信息,请点击此处
此处引用前面的问题
我认为这是您的问题:
file.write(time + 'n')
time
变量不是字符串。你想要的是:
file.write(data+ 'n')
Datetime是一个对象,它不会自动格式化自己。您需要使用strftime[1]才能使它看起来像您想要的样子。根据您的文件名,您可以通过以下操作在年月日进行设置:
timeString = time.strftime('%Y-%d-%m')
如果你想要自epoch以来的秒数,你可以做
timeString = time.strftime('%s')
然后您应该打印timeString,而不是在写入文件时的时间:
file.write(timeString + 'n')
[1] -https://docs.python.org/2/library/datetime.html#strftime-strptime行为
MyColor = random.choice(['red','blue','green','pink','purple','orange','yellow','black','white'])
time = str(datetime.datetime.now())
data = MyColor + " " + time
msg = visual.TextStim(win, text=Phrase,pos=[0,4],color=MyColor)
msg.draw()
win.flip()
core.wait(.1)
file.write(data + 'n')
谢谢!感谢你的帮助,我想我已经想通了。
要连接它们,必须对datetime对象执行str((操作。还有:
f = open('2015-07-15-Random-Output.txt', 'w')
print f
file = open ('2015-07-15-Random-Output.txt', 'w')
如果你只是删除文件=打开的行,然后这样做,这有点多余,也更简单:
from psychopy import visual, core
import random
import time
import datetime
import time
from time import strftime
with open('2015-07-15-Random-Output.txt', 'w') as f:
print f
win = visual.Window([800,800],monitor="testmonitor", units="deg")
HolaMundo = "Hola Mundo"
for frameN in range(10):
MyColor = random.choice(['red','blue','green','pink','purple','orange','yellow','black','white'])
time = datetime.datetime.now()
print time
data = MyColor + str(time)
msg = visual.TextStim(win, text=HolaMundo,pos=[-4,0],color=MyColor)
msg.draw()
win.flip()
core.wait(.1)
datetime.datetime.now
f.write(time + 'n')
f.close()