我正在尝试格式化日期,即从Jan
到JA
,Feb
到FE
。我有一个字典来做这个,但我的代码只能随机工作,例如,有时每4次,有时每24次。我是Python的新手,我无法理解这一点。以下代码的输出大多数情况下为16Jun28
,但有时正确16JN28
。
import datetime
month_code = {'Jan': 'JA',
'Feb': 'FE',
'Mar': 'MR',
'Apr': 'AL',
'May': 'MA',
'Jun': 'JN',
'Jul': 'JL',
'Aug': 'AU',
'Sep': 'SE',
'Oct': 'OC',
'Nov': 'NO',
'Dec': 'DE'}
today = datetime.datetime.now()
DD = datetime.timedelta(days=90)
use_by = today + DD
use_by_str = use_by.strftime("%y-%b-%d")
def label_function():
month = use_by.strftime("%b")
year = use_by.strftime("%y")
day = use_by.strftime("%d")
return year + month + day
line = label_function()
for k, v in month_code.items():
Result = line.replace(k, v)
print(Result)
答案 0 :(得分:2)
您正在遍历您的字典以将您的3个字符月份名称替换为2个字符,但您始终将结果放在另一个变量中,而不是变异line
本身。
你要找的是
for k, v in month_code.items():
line = line.replace(k, v)
顺便说一下,为什么不让你的label_function
返回日期字符串的元组,然后你只需要用1次查找来改变1个值。
def label_function():
month = use_by.strftime('%b')
year = use_by.strftime('%y')
day = use_by.strftime('%d')
return year, month, day
year, month, day = label_function()
result = year + month_code[month] + day
答案 1 :(得分:0)
Christian已经展示了一种更好的方式来实现您的需求。我会尝试解释这个错误。
它是随机工作的,因为代码中的逻辑错误与字典的随机排序相结合。
您有两个变量,line
和Result
。假设line
是' 16Feb28'。你的代码
line
,尝试用JA替换Jan,并将结果(未更改)放入Result
。line
,尝试用FE替换2月,并将结果(16FE28)放入Result
。line
(16Feb28),尝试用MR替换Mar,并将结果(16Feb28)放入Result
。line
(16Feb28),尝试用DE替换Dec,并将结果(16Feb28)放入Result
。有时有效的原因在于,实际上字典不会按照您在源代码中编写它们的顺序进行迭代,而是以随机字典进行迭代,因此匹配条目2月 - > ; FE有时恰好是最后一个。
为什么订单是随机的?见Why is the order in dictionaries and sets arbitrary?