python 时间戳 字符串_时间戳更改的Python字符串

作者探讨了在Python中使用datetime包初始化字符串变量时遇到的问题,尤其是在nose单元测试环境下,字符串看似在后续操作中被重新计算。寻求理解这种行为是否正常及如何避免,以确保变量值在多次调用中的稳定性。
摘要由CSDN通过智能技术生成

我试图使用datetime包在Python中初始化一个字符串变量。我希望字符串在初始化后保持不变,但是由于某种奇怪的原因(至少对我来说很奇怪),它正在发生变化。在

基本上,当我试图:timestamp = datetime.datetime.now().strftime('%m-%d-%Y.%I_%M_%S_%p')

base_directory = "C:\\Users\\Ben\\report_" + timestamp + "\\"

print base_directory #prints C:\Users\Ben\report_02-13-2015_02_02_24_PM

time.sleep(5)

logs_directory = base_directory + "logs\\"

当我回去使用logs_directory变量时,我希望它是

^{pr2}$

然而,事实是:C:\Users\Ben\report_02-13-2015_02_02_29_PM\logs\ #!!!

这就好像当我访问logs directory变量时,它会返回并重新评估base_directory变量,而不是检索base峎directory已经设置为的值。这是Python中预期的功能吗?我不这么认为,因为我似乎无法从空闲shell触发这个问题——只有在我从pydev运行Python程序时才会发生。但是,如果这是预期的功能,我如何重写代码以获得预期的结果?谢谢!在

我不确定它是否相关,但我正在nose单元测试中访问这个变量。这是Python2.7中的。在

更新:这里有一些独立的代码,可以更好地说明发生了什么。事实上,它确实在某种程度上与鼻子有关:import nose, os, sys, time

timestamp = time.strftime('%m-%d-%Y.%I_%M_%S_%p')

base_directory = "C:\\Users\\Ben\\Desktop\\report_" + timestamp + "\\"

logs_directory = base_directory + "logs\\"

def test_me():

print base_directory

print logs_directory

if __name__ == '__main__':

os.makedirs(base_directory)

os.makedirs(logs_directory)

print base_directory

print logs_directory

time.sleep(5)

#Without the nocapture argument, nose will internally log all

#stdout output, and will not output anything to the console.

argv = (sys.argv[:])

argv.insert(1, "--nocapture")

nose.main(argv=argv) #This will run test_me()

输出如下:C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_37_PM\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_37_PM\logs\

我期待着:C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\

C:\Users\Ben\Desktop\report_02-13-2015.04_27_32_PM\logs\

怎么回事?为什么nose要重新计算已经初始化的字符串?我如何重写我的代码,使之符合我的预期?谢谢!在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值