我是python的新手,我编写了一个脚本,将进入的字符串日期转换为datetime格式化.我的问题是无法将datetime对象转换回字符串进行操作.我有一个约会,例如2011-08-10 14:50:10我需要T在日期和时间之间添加一个日期和Z结尾.不幸的是我使用python 2.3作为我的应用程序将只接受.
我的代码如下:
fromValue= ''
fromValue = document.Get(self._generic3)
fromValue = fromValue[:fromValue.rindex(" ")]
fromValue = datetime.datetime.fromtimestamp(time.mktime(time.strptime(fromValue,"%a, %d %b %Y %H:%M:%S")))
Run Code Online (Sandbox Code Playgroud)
toValue = fromValue.strftime("%Y-%m-%dT %H:%M:%SZ")
Run Code Online (Sandbox Code Playgroud)
这应该工作正常.datetime.strftime可以在Python 2.3上找到.
如果可能的话,你最好升级到至少 Python 2.5.Python 2.3多年来甚至没有收到过安全补丁.
编辑:此外,您不需要在Python中初始化或声明变量; 这fromValue= ''对你的程序没有影响.
编辑2:在评论中,你似乎已经说过你已经在一个字符串中已经有了几乎正确的格式:
"2011-08-08 14:15:21"
Run Code Online (Sandbox Code Playgroud)
所以就这么做
'T'.join("2011-08-08 14:15:21".split()) + 'Z'
Run Code Online (Sandbox Code Playgroud)
如果你想添加字母,而它是一个字符串.