首页 > 解决方案 > 拆分未格式化的日期/时间字符串并分配给各个变量以连接

问题描述

我试图使这个输入日期和时间结构......

core.setDate("19411213T1234","UTC");

(注意中间的“T”)

……进入这个……

core.setDate("1941-12-13T12:34:00","UTC");

我尝试使用 splitdate(),但“T”不允许该函数产生正确的输出。我打算用“content.find”将分割的字符串分配给各个变量来定位字符串的开头。仅供参考 - 结尾的两个字母是“st”,它引用找到的位置的开始,“nd”引用结束位置。我希望这是有道理的?

这是我一直在使用的代码...

# Initial Opening of "startup.ssc" for writing.
stella = open(""+stellocation+"\\scripts\\startup.ssc",'w')

# Write raw Date and Time line
stella.write(f'core.setDate("{date}T{time}:00","UTC");\n')

# Initial close of startup.ssc for safety
stella.close()

#Reopening of startup.ssc
stella = open(""+stellocation+"\\scripts\\startup.ssc",'w')

# Format raw Date and Time line
startdatetime = content.find("core.setDate")
yearst = content.find("(\"",startdatetime)
yearnd = content.find("",startdatetime+4)
monthst = content.find("",yearnd)
monthnd = content.find("",monthst+2)
dayst = content.find("",monthnd)
daynd = content.find("",dayst+2)
hourst = content.find("",daynd+1)
hournd = content.find("",hourst+2)
minutest = content.find("",hournd)
minutend = content.find("",minutest+2)

# Write Formatted Date and Time line
stella.write(f'core.setDate("{yearnd}-{monthnd}-{daynd}T{hournd}:{minutend}:00","UTC");\n')

代码没有产生我上面显示的输出,而是产生了这个错误的文本......

core.setDate("3-5-7T10:12:00","UTC");

我不知道为什么?

标签: python

解决方案


尝试这个:-

def reformat(d):
    return f'{d[:4]}-{d[4:6]}-{d[6:11]}:{d[11:13]}:00'


print(reformat("19411213T1234"))

推荐阅读